2

我的产品型号是这样的:

<?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来添加、删除和获取数据收藏夹

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

还是有更好的方法来做到这一点?

4

0 回答 0