从belongsToMany关系Laravel获取指定记录

时间:2016-03-14 16:41:02

标签: php laravel eloquent

如果我有properties表和另外两个表:

 *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)

在Property.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

2 个答案:

答案 0 :(得分:2)

由于值在您的数据透视表上,您需要告诉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;

或者,在您的Property模型中添加一个getter(为您执行此操作)(您仍然需要将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')的房间数。

答案 1 :(得分:0)

首先,您必须告诉您的关系,以使您的其他字段可用。您可以使用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;
}

您可以在{{3>}的检索中间表列标题下阅读有关此内容的更多信息。

相关问题