Laravel Polymorphic Relations Has Many Through

前端 未结 5 1742
闹比i
闹比i 2020-12-09 09:37

I have a Subscriber Model

// Subscriber Model

id
user_id
subscribable_id
subscribable_type

public function user()
{
    return $this->belongsTo(\'App\\U         


        
5条回答
  •  温柔的废话
    2020-12-09 09:49

    In addition to Matt's approach, the following code also could be another solution:

    //Topic Model
    public function users()
    {
        return $this->belongsToMany(User::class, 'subscribers', 'subscribale_id', 'user_id')
            ->where('subscribale_type', static::class);
    }
    

    In this way Subscriber treated as a pivot table and second argument is table name for pivot.

    The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to. Read more here.

    Consider the where clause after belongsToMany to filter only the current model.

提交回复
热议问题