简体   繁体   中英

updateOrCreate for polymorphic relation?

Is there a way to use updateOrCreate() or similar method for polymorphic relationship?

Problem with using updateOrCreate method I wouldn't know the id in the polymorphic table.

Currently doing like this:

if ($request->has('meta.description')) {
    $description = $cat->tags()->where('key', 'description')->first();

    if (is_null($description)) {
        $cat->tags()->create([
            'client_id' => client()->id,
            'key'       => 'description',
            'value'     => $request->input('meta.description'),
        ]);
    } else {
        $description->update([
            'value' => $request->input('meta.description'),
        ]);
    }

}

Tag method like like this Cat model:

public function tags()
{
    return $this->morphMany('App\Tag', 'taggable', 'table_name', 'table_id');
}

You need to pass in a second parameter to updateOrCreate . Try splitting the array up into two like so:

$cat->tags()->updateOrCreate(
    [
        'client_id' => client()->id,
        'key'       => 'description'
    ],
    [
        'value'     => $request->input('meta.description')
    ]
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM