[英]Laravel 5 relationship between to belong
I have a three table vendor
banquet
project
, and the relationship is like following description: 我有一个三桌
vendor
banquet
project
,关系如下:
* vendor
hasMany banquet
and project
*
vendor
banquet
和project
class Vendor extends Model
{
.....
public function project()
{
return $this->hasMany('App\Entities\Project' ,'vendorId' ,'id');
}
public function banquet()
{
return $this->hasMany('App\Entities\Banquet' ,'vendorId' ,'id');
}
}
* banquet
belongsTo vendor
*
banquet
属于vendor
class Banquet extends Model
{
...
public function vendor()
{
return $this->belongsTo('App\Entities\Vendor' ,'vendorId' ,'id');
}
}
* project
belongsTo vendor
*
project
属于vendor
class Project extends Model
{
...
public function vendor()
{
return $this->belongsTo('App\Entities\Vendor' ,'vendorId' ,'id');
}
}
And some situation, I just have banquet.id
that can find banquet
data and at the same time, need to get all of the same vendorId project
data within a query. 在某些情况下,我只有
banquet.id
可以找到banquet
数据,同时需要在查询中获得所有相同的vendorId project
数据。
How can I defined the new relationship between project
and banquet
? 我怎样才能定义
project
和banquet
之间的新关系? or any idea can find the two kinds data in once query? 或任何想法可以在一次查询中找到两种数据?
You can try as: 您可以尝试:
$banquet = Banquet::where('id', $banquet_id)->with('vendor.project')->first();
then get all of the same vendorId project
data as: 然后得到所有相同的vendorId
project
数据:
$banquet->vendor->project;
it gives the collection of the project. 它给出了项目的集合。
OR 要么
You can use has-many-through
relation to access project
from banquet
model. 您可以使用
has-many-through
关系从banquet
模型访问project
。
For this create a following function in Banquet.php
class 为此,在
Banquet.php
类中创建以下函数
public function project()
{
return $this->hasManyThrough('App\Entities\Project', 'App\Entities\Banquet');
}
then your query will be like: 然后你的查询将是:
$banquet = Banquet::where('id', $banquet_id)->with('project')->first();
$banquet->project;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.