Laravel Polymorphic Relations Has Many Through

Laravel hasManyThrough a polymorphic relation

Specify the custom foreign key and add a constraint for the owner_type column:

public function transactions() {
return $this->hasManyThrough(Transaction::class, Driver::class, null, 'owner_id')
->where('owner_type', Driver::class);
}

Without the constraint, you would get transactions of different owners that have the same id.

hasManyThrough with morph

So you actually need something like this:

public function project()
{
return $this->hasManyThrough('App\Project', 'App\User', 'assignable_id')
->where(
'assignable_type',
array_search(static::class, Relation::morphMap()) ?: static::class
);
}

or

public function project()
{
return $this->belongsToMany(Project::class, 'assignable', 'assignable_id', 'project_id')
->where('assignable_type', static::class);
}

Ref: Laravel Polymorphic Relations Has Many Through

Your working solution:

public function projects() {
return $this->hasManyThrough(
Project::class,
User::class,
'id',
'assignable_id',
)->where(
'assignable_type', User::class
)->orWhere(function ($q) {
$q->where('assignable_type', Team::class)
->whereIn('assignable_id', $this->teams->pluck('id'));
});
}

Problem with Polymorphic Relationships in Laravel

Based on the reply by https://stackoverflow.com/users/8158202/akhzar-javed I figure it out, but I had to change the code a bit:

Instead of the code in the answer, I had to use the following:

     public function details()
{
Relation::morphMap([
'person' => 'App\Models\Persondetails',
'company' => 'App\Models\Companydetail',
]);
return $this->morphTo(__FUNCTION__, 'group', 'id', 'person_id');
}

laravel hasMany polymorphic relationship in where clause

I assume you are wanting to order pictures by the most likes.

In which case, you want something like this:

Picture::withCount('likes')->where('picture_type', 'food')->orderBy('likes_count', 'desc')->first(); 


Related Topics



Leave a reply



Submit