[英]How to get properies of a relationship as comma separated values in laravel?
I have a ManyToMany
relationship for example Facility and Home so here is the example of the relationship: 我有一个
ManyToMany
关系,例如Facility和Home,所以这是关系的示例:
public function facility()
{
return $this->belongsToMany(facility::class)->withPivot('is_free');
}
and in facility
I have: 在
facility
我有:
public function home()
{
return $this->belongsToMany(Home::class)->withPivot('is_free');
}
and in some controller
I do like below : 在某些
controller
我喜欢以下代码:
$data = Home::with('facility')->get;
it gives me the result like below : 它给我的结果如下:
{
name: example,
id: 1,
facility: {
id: 1,
name:item1,
},
{
id: 1,
name:item1,
},
{
id: 1,
name:something,
}
}
now i want it comma separated like below : 现在我希望它用逗号分隔,如下所示:
{
name:example,
id : 1,
some other fileds ,
,
,
facility: {item1,item2,item3,item4,. . .
}
}
so I want them comma separated and only pick some certain columns from it 所以我希望他们用逗号分隔,并且只从中选择某些列
I recommend using a custom attribute for this. 我建议为此使用自定义属性 。
public function getFacilityDataAttribute()
{
return implode(", ", $this->facility->getAttributes());
}
And inside Home class: 在Home类中:
class Home extends Model
{
protected $appends = ['facility_data'];
}
If you want to restrict the results for facility, you can do this. 如果要限制设施的结果,可以执行此操作。
public function facility()
{
return $this->belongsToMany(facility::class)->withPivot('is_free')->where('some_field','some_value');
}
if you want to join the results by comma, you can do this. 如果要用逗号加入结果,可以执行此操作。
foreach($homes as $home) {
$home->computed_field = $home->facility->pluck('name')->implode(',');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.