从属于多关系拉拉维尔获取指定记录


Get specified record from belongsToMany relation Laravel

如果我有properties表和其他 2 个表:

 *property_characteristics
  - property_id (i.e. 1)
  - characteristic_id (i.e. 5 - join with default_characteristics)
  - value (i.e. 3 - aka 3 rooms)
 *default_characteristics
  - id (i.e. 5)
  - name (i.e. rooms)

在属性.php模型中,我有:

public function characteristics()
{
return $this->belongsToMany('Proactiv'DefaultCharacteristic', 'property_characteristics', 'property_id', 'characteristic_id');
}

如何从以下位置获取住宿的房间数量(价值从property_characteristics开始):

$property = Properties::find(1);

我需要这样的东西:

$property->characteristics->rooms // should return 3 which is the value columns on property_characteristics table

由于该值在您的数据透视表上,您需要告诉Laravel这个额外的字段。添加到您的belongsToMany行中,使:

return $this->belongsToMany('Proactiv'DefaultCharacteristic', 'property_characteristics', 'property_id', 'characteristic_id')
    ->withPivot('value');

然后选择具有所需名称的特征,rooms ,并获取值:

echo $property->characteristics()->with('name', 'rooms')->first()->pivot->value;

或者,将一个 getter 添加到您的 Property 模型中,该模型会为您执行此操作(您仍然需要将该withPivot部分添加到关系中):

public function getRoomsAttribute()
{
    return $this->characteristics()
        ->where('name', 'rooms')
        ->first()
        ->pivot
        ->value;
}

然后,您可以使用$property->rooms以与最初想要的方式类似的方式获取房间数量。

或者你可以概括这一点以获得任何特征:

public function getCharacteristic($name)
{
    return $this->characteristics()
        ->where('name', $name)
        ->first()
        ->pivot
        ->value;
}

然后获取带有$property->getCharacteristic('rooms')的房间数量.

首先,您必须告诉您的关系以使您的附加字段可用。您可以使用 withPivot() 方法执行此操作:

public function characteristics() {
    return $this->belongsToMany('Proactiv'DefaultCharacteristic', 'property_characteristics', 'property_id', 'characteristic_id')
        ->withPivot('value');
}

现在,您可以在数据透视表上访问您的值。你这样做是这样的:

$property = Properties::find(1);
foreach ($property->characteristics as $characteristic) {
    echo $characteristic->pivot->value;
}

您可以在此处的文档"检索中间表列"标题下阅读有关此内容的详细信息。