获取额外的数据透视表列laravel的值 [英] getting the value of an extra pivot table column laravel
问题描述
我有一个phone_models,phone_problems和一个phone_model_phone_problem数据透视表.数据透视表有一个额外的价格"列.
I have a phone_models, phone_problems, and a phone_model_phone_problem pivot table. The pivot table has an extra column 'price'.
PhoneModel:
PhoneModel:
class PhoneModel extends \Eloquent
{
public function problems()
{
return $this->belongsToMany('RL\Phones\Entities\PhoneProblem')->withPivot('price');
}
}
PhoneProblem:
PhoneProblem:
class PhoneProblem extends \Eloquent
{
public function models()
{
return $this->belongsToMany('PhoneModel')->withPivot('price');
}
}
我想做的是获取具有特定问题的特定手机的价格.
What I'm trying to do is get the price of a specific phone with a specific problem.
这就是我现在的方式,但是我觉得Laravel具有内置的Eloquent功能,我找不到用更简单的方式做到这一点:
This is how I have it now but I feel like Laravel has a built in Eloquent feature I can't find to do this in a much simpler way:
$model = $this->phoneService->getModelFromSlug($model_slug);
$problem = $this->phoneService->getProblemFromSlug($problem_slug);
这一切都是从他们的中选择特定的型号和问题.
all this does is select the specific model and problem from their slug.
然后我要做的就是凭这些凭证获取价格,如下所示:
then what I do is with those credentials I get the price like so:
$row = DB::table('phone_model_phone_problem')
->where('phone_model_id', '=', $model->id)
->where('phone_problem', '=', $problem->id)
->first();
所以现在我可以像$row->price
这样获得价格,但我觉得需要一种更简单,更"Laravel"的方式来实现此目的.
so now I can get the price like so $row->price
but I feel like there needs to be a much easier and more 'Laravel' way to do this.
推荐答案
在Eloquent中使用多对多关系时,结果模型将自动分配一个pivot
属性.通过该属性,您可以访问数据透视表列.
尽管默认情况下,枢轴对象中只有键.为了将列也放入其中,您需要在定义关系时指定它们:
When using Many to Many relationships with Eloquent, the resulting model automatically gets a pivot
attribute assigned. Through that attribute you're able to access pivot table columns.
Although by default there are only the keys in the pivot object. To get your columns in there too, you need to specify them when defining the relationship:
return $this->belongsToMany('Role')->withPivot('foo', 'bar');
如果您需要更多与Eloquent配置关系的帮助,请告诉我.
If you need more help the task of configuring the relationships with Eloquent, let me know.
修改
要查询价格,请执行此操作
To query the price do this
$model->problems()->where('phone_problem', $problem->id)->first()->pivot->price
这篇关于获取额外的数据透视表列laravel的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!