繁体   English   中英

如何在laravel中以逗号分隔的值获取关系的属性?

[英]How to get properies of a relationship as comma separated values in laravel?

我有一个ManyToMany关系,例如Facility和Home,所以这是关系的示例:

public function facility()
{
    return $this->belongsToMany(facility::class)->withPivot('is_free');
}

facility我有:

public function home()
{
   return $this->belongsToMany(Home::class)->withPivot('is_free');
}

在某些controller我喜欢以下代码:

$data = Home::with('facility')->get;

它给我的结果如下:

{
    name: example,
    id: 1,
    facility: {
        id: 1,
        name:item1,
    },
    {
        id: 1,
        name:item1,
    },
    {
        id: 1,
        name:something,
    }
}

现在我希望它用逗号分隔,如下所示:

{   
    name:example,
    id : 1,
    some other fileds ,
    ,
    , 
         facility: {item1,item2,item3,item4,. . .
    }
}

所以我希望他们用逗号分隔,并且只从中选择某些列

我建议为此使用自定义属性

public function getFacilityDataAttribute()
{
    return implode(", ", $this->facility->getAttributes());
}

在Home类中:

class Home extends Model
{
    protected $appends = ['facility_data'];
}

如果要限制设施的结果,可以执行此操作。

public function facility()
{
    return $this->belongsToMany(facility::class)->withPivot('is_free')->where('some_field','some_value');
}

如果要用逗号加入结果,可以执行此操作。

foreach($homes as $home) {
  $home->computed_field = $home->facility->pluck('name')->implode(',');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM