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
Subtracting a Certain Number of Hours, Days, Months or Years from Date
Using the Browser Prompt to Download a File
Replacing .PHP Ext with .HTML Through .Htaccess
500 Server Error: Premature End of Script Headers:
Get Key of Multidimensional Array
File_Exists() Returns False, But the File Does Exist
Conditional Statements in PHP Code Between HTML Code
Mysql_Connect (Localhost/127.0.0.1) Slow on Windows Platform
How to Send Email from Local Wamp Server Using PHP
Session_Start() Takes Very Long Time
Detect Mobile Devices - and Tablet Devices
Differencebetween Get_Result() and Store_Result() in PHP
Installing Imagemagick Extension with PHP/Windows
What's the Best Way to Get the Fractional Part of a Float in PHP