如何在Laravel 5.6中添加、删除和获取具有多态关系的产品的收藏夹?

如何在Laravel 5.6中添加、删除和获取具有多态关系的产品的收藏夹?,laravel,relationship,laravel-eloquent,laravel-5.6,has-many-polymorphs,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'); } } public function

我的产品模型如下:

<?php
...
class Product extends Model
{
    ...
    protected  $fillable = ['name','photo','description',...];
    public function favorites(){
        return $this->morphMany(Favorite::class, 'favoritable');
    }
}
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\u id
来添加、删除和获取数据

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


还是有更好的方法

如果代码有效,您需要审查或如何改进,您应该询问,如果唯一的
最受欢迎的类型是产品,那么就不需要使用多态性relationship@Ben我认为它可以使用多态关系添加、删除和获取数据。你得到答案了吗?@João Mantovani还没有。对于我的案例,我仍然使用上述方法
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;
}