[英]Can I join a related table using Lauravel/Eloquent eager loading?
I'm having trouble understanding how eager loading works with Lauravel/Eloquent. 我很难理解Lauravel / Eloquent如何进行热切的加载。 I'd like to grab all clients, do some stuff with them, and output their brand_name
. 我想吸引所有客户,与他们一起做一些事情,并输出他们的brand_name
。 I have these tables: 我有这些表:
Clients
+-------------------+
| Field |
+-------------------+
| client_id |
| client_name |
| client_brand_id |
+-------------------+
Brands
+-------------------+
| Field |
+-------------------+
| brand_id |
| brand_name |
+-------------------+
In the client model I have the relationship: 在客户端模型中,我有以下关系:
public function brand()
{
return $this->hasOne('Brand', 'client_brand_id', 'brand_id');
}
And inverse in the brands model: 与品牌模型相反:
public function clients()
{
return $this->hasMany('Client', 'brand_id', 'client_brand_id');
}
I want to do this, but it doesn't work: 我想这样做,但是不起作用:
foreach( Client::with( 'brand' )->get( array('client_id', 'client_name' ) ) as $client ){
echo $client->brand->brand_name;
}
You need to define your brand
relationship in your client
model like this: 您需要像这样在client
模型中定义brand
关系:
public function brand()
{
return $this->belongsTo('Brand', 'client_brand_id', 'brand_id');
}
The reason is that you have a one-to-many relationship, not a one-to-one relationship between clients and brands. 原因是您与客户和品牌之间存在一对多的关系,而不是一对一的关系。
Also, you need to get the complete model for the eager loaded relationship to be available, like so: 另外,您需要获取完整的模型以使渴望的加载关系可用,如下所示:
foreach( Client::with( 'brand' )->get() as $client )
{
echo $client->brand->brand_name;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.