如何在Laravel 5.6中添加,删除和获得具有多态关系的产品的最爱?

时间:2018-03-27 12:32:55

标签: laravel relationship laravel-eloquent laravel-5.6 has-many-polymorphs

我的产品型号如下:

<?php
...
class Product extends Model
{
    ...
    protected  $fillable = ['name','photo','description',...];
    public function favorites(){
        return $this->morphMany(Favorite::class, 'favoritable');
    }
}

我最喜欢的模特:

<?php
...
class Favorite extends Model
{
    ...
    protected $fillable = ['user_id', 'favoritable_id', 'favoritable_type'];
    public function favoritable()
    {
        return $this->morphTo();
    }
}

我的雄辩查询laravel添加,删除和得到这样:

public function addWishlist($product_id)
{
    $result = Favorite::create([
        'user_id'           => auth()->user()->id,
        'favoritable_id'    => $product_id,
        'favoritable_type'  => 'App\Models\Product',
        'created_at'        => Carbon::now()
    ]);
    return $result;
}
public function deleteWishlist($product_id)
{
    $result = Favorite::where('user_id', auth()->user()->id)
                      ->where('favoritable_id', $product_id)
                      ->delete();
    return $result;
}
public function getWishlist($product_id)
{
    $result = Favorite::where('user_id', auth()->user()->id)
                      ->where('favoritable_id', $product_id)
                      ->get();
    return $result;
}

从上面的代码中,我使用参数product_id来添加,删除和获取数据

我想问的是:上述是否是使用多态关系添加,删除和获取数据的正确方法?

或者有更好的方法吗?

0 个答案:

没有答案