How can I add, delete and get a favorite from prod

2019-03-03 12:53发布

问题:

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?