[英]Laravel Eloquent Relation Query - Get data along with relation attribute
I need help to retrieve eloquent relational data. 我需要帮助来检索雄辩的关系数据。
Let's say I have this eloquent relation: 假设我有这种雄辩的关系:
Company 公司
Attribute: (id, code, name, status) 属性:(ID,代码,名称,状态)
Relation: 关系:
public function sites(){
$this->hasMany(\App\Models\Site::class);
}
Site 现场
Attribute: (id, company_id, code, name, status) 属性:(id,company_id,代码,名称,状态)
Relation: 关系:
public function company(){
$this->belongsTo(\App\Models\Company::class);
}
I want to retrieve all site data along with it's company name, eg: 我想检索所有站点数据及其公司名称,例如:
[
{
"id":7,
"company_id":1,
"company_name":"Company 1",
"code":"S001",
"name":"Site 001",
"status":"Active"
},
{
"id":8,
"company_id":1,
"company_name":"Company 1",
"code":"S002",
"name":"Site 002",
"status":"Active"
}
]
1 - I've already tried with this method: 1-我已经尝试过这种方法:
$sites = Site::with('company')->get();
dd($sites->toJson());
but it gives me: 但这给了我:
[
{
"id":7,
"company_id":1,
"code":"S001",
"name":"Site 001",
"status":"Active",
"company":{
"id":1,
"code":"C001",
"name":"Company 1",
"status":"Active"
}
},
{
"id":8,
"company_id":1,
"code":"S002",
"name":"Site 002",
"status":"Active",
"company":{
"id":1,
"code":"C001",
"name":"Company 1",
"status":"Active"
}
},
]
2 - For now, I use this way to get the data. 2-现在,我使用这种方式来获取数据。 But I think there's another best way without loop the whole data just to get some specific relation attribute:
但我认为还有另一种最好的方法,即不循环整个数据,而只是获取一些特定的关系属性:
$sites = Site::get();
foreach ($sites as $site){
$site['company_name'] = $site->company()->first()->name;
}
dd($sites->toJson());
Actually, how is the best way to get the data I want? 其实,获取所需数据的最佳方法是什么? Is it possible to not use loop and just use Eloquent relation query?
是否可以不使用循环而仅使用雄辩的关系查询? Thank you.
谢谢。
Your best bet would be to create an accessor on your Site
model: 最好的选择是在您的
Site
模型上创建一个访问器 :
public function getCompanyNameAttribute()
{
return optional($this->company)->name;
}
^ The optional()
helper makes it so, that this won't throw an error if a site doesn't have a company. ^
optional()
帮助器做到了这一点,如果站点没有公司,这不会引发错误。 You might not need it depending on your database set up. 您可能不需要它,具体取决于您的数据库设置。
You can then add the accessor to $appends
array in the model, so that it becomes visible in JSON dumps: 然后,您可以将访问器
$appends
到模型中的$appends
数组中,以使其在JSON转储中可见:
protected $appends = ['company_name'];
I would also recommend you to eager load the company with sites every time, like you did in your first example - to avoid n + 1
: 我还建议您每次都像在第一个示例中一样,急于向公司加载网站,以避免
n + 1
:
Site::with('company')->get()
Additionally, if you'd like to hide the company
object, you can do that with protected $hidden = ['company']
in the model. 另外,如果您想隐藏
company
对象,则可以在模型中使用protected $hidden = ['company']
来实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.