I have the three tables articles
, locations
and companies
. One row of each table can be linked with another row form one of the other tables over a fourth table calles links
, where links
looks like:
For example, the article
with the ID 1 could have a connection to the locations
ID 1:
and the a connection with the company 3:
Which laravel relations would I need here? Its some kind of polymorphic many to many relation?
Actually this works with the links table
class Article extends Model
{
use HasFactory;
public function companies()
{
return $this->morphToMany(Company::class, 'to', 'links', 'from_id', 'to_id', 'id', 'id', 'to');
}
public function locations()
{
return $this->morphToMany(Location::class, 'to', 'links', 'from_id', 'to_id', 'id', 'id', 'to');
}
}
Following test data in links table
This query
Article::with(['companies', 'locations'])->first();
//output
App\Models\Article {#2010
id: 1,
title: "Et molestiae consequuntur harum provident officia neque.",
created_at: "2020-12-07 20:18:42",
updated_at: "2020-12-07 20:18:42",
companies: Illuminate\Database\Eloquent\Collection {#2003
all: [
App\Models\Company {#2007
id: 3,
name: "Ledner-Schumm",
created_at: "2020-12-07 20:18:42",
updated_at: "2020-12-07 20:18:42",
pivot: Illuminate\Database\Eloquent\Relations\MorphPivot {#2004
from_id: 1,
to_id: 3,
to_type: "App\Models\Company",
},
},
],
},
locations: Illuminate\Database\Eloquent\Collection {#1999
all: [
App\Models\Location {#1997
id: 2,
name: "Maiamouth",
created_at: "2020-12-07 20:19:08",
updated_at: "2020-12-07 20:19:08",
pivot: Illuminate\Database\Eloquent\Relations\MorphPivot {#2001
from_id: 1,
to_id: 2,
to_type: "App\Models\Location",
},
},
],
},
}
And for the inverse relation
class Company extends Model
{
use HasFactory;
public function articles()
{
return $this->morphedByMany(Article::class, 'from', 'links', 'to_id', 'from_id', 'id', 'id');
}
}
Query
Company::with('articles')->find(3);
//Output
App\Models\Company {#2025
id: 3,
name: "Ledner-Schumm",
created_at: "2020-12-07 20:18:42",
updated_at: "2020-12-07 20:18:42",
articles: Illuminate\Database\Eloquent\Collection {#2026
all: [
App\Models\Article {#2024
id: 1,
title: "Et molestiae consequuntur harum provident officia neque.",
created_at: "2020-12-07 20:18:42",
updated_at: "2020-12-07 20:18:42",
pivot: Illuminate\Database\Eloquent\Relations\MorphPivot {#2049
to_id: 3,
from_id: 1,
from_type: "App\Models\Article",
},
},
],
},
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.