How can I add, delete and get a favorite from product with polymorphic relationship, in Laravel 5.6?

只愿长相守 提交于 2020-01-21 20:09:08

问题


My product model like this :

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

My favorite model like this :

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

My eloquent query laravel to add, delete and get like this :

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;
}

From the code above, I'm using parameter product_id to add, delete and get data favorite

What I want to ask here is : Whether the above is the correct way to add, delete and get data using polymorphic relationship?

Or is there a better way to do that?

来源:https://stackoverflow.com/questions/49512956/how-can-i-add-delete-and-get-a-favorite-from-product-with-polymorphic-relations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!