updating a relationship in laravel

2019-07-21 06:17发布

问题:

I have a model that has a relationship like this

public function users(){
    return $this->belongsToMany(User::class);
}
public function latestUrlStatus(){
    return $this->hasOne(UrlStatus::class)->latest();
}

from my controller i can save from many to many relationship like this (SUCCESS NO PROBLEM)

public function update(Request $request, $id)
{
    $updateUrl = Url::findOrFail($id);
    $updateUrl->url = $request->input('url');
    $updateUrl->description = $request->input('description');
    $updateUrl->users()->sync(array_pluck($request->input('selectedTags'), 'id'));
    $updateUrl->save();

        if($updateUrl){
            return new UrlsResource($updateUrl);
        }
}

but when i add this code to save from another relation

public function update(Request $request, $id)
{
    $updateUrl = Url::findOrFail($id);
    $updateUrl->url = $request->input('url');
    $updateUrl->description = $request->input('description');
    $updateUrl->users()->sync(array_pluck($request->input('selectedTags'), 'id'));
    $updateUrl->save();

    //THIS CODE UP TO LAST
    $httpCode = check_http_header($request->input('url'));
    $status = "UP";

    $url = Url::with('latestUrlStatus','users')->findOrfail($id);
    $updateUrl->latestUrlStatus()->status_code = $httpCode;
    $updateUrl->latestUrlStatus()->status = $status;
    $updateUrl->push();
    if($updateUrl){
       return new UrlsResource($updateUrl);
    }
}

it doesnt update the latest url status. I'm sorry just new to framework. Thanks in advance.

回答1:

Change in your update code $updateUrl->latestUrlStatus() to $updateUrl->latestUrlStatus like this

$updateUrl = Url::with('latestUrlStatus','users')->findOrfail($id);
$updateUrl->latestUrlStatus->status_code = $httpCode;
$updateUrl->latestUrlStatus->status = $status;
$updateUrl->push();
if($updateUrl){
   return new UrlsResource($updateUrl);
}

$updateUrl->latestUrlStatus() return query Builder instance, where has $updateUrl->latestUrlStatus return UrlStatus instance, thats what you need.



回答2:

You can try

$updateUrl->latestUrlStatus()->save()

instead of

$updateUrl->push();

$updateUrl->push saves a model ($updateUrl) and all it's relations. If it doesn't work and $updateUrl->latestUrlStatus->save() works, then you know that $updateUrl just doesnt recognize ->latestUrlStatus() as a relation, probably because of you using the function method latestUrlStatus(), to access the submodel, not the magic method ->latestUrlStatus