【发布时间】:2014-12-21 09:34:10
【问题描述】:
我有一个 phone_models、phone_problems 和一个 phone_model_phone_problem 数据透视表。数据透视表有一个额外的列“价格”。
手机型号:
class PhoneModel extends \Eloquent
{
public function problems()
{
return $this->belongsToMany('RL\Phones\Entities\PhoneProblem')->withPivot('price');
}
}
电话问题:
class PhoneProblem extends \Eloquent
{
public function models()
{
return $this->belongsToMany('PhoneModel')->withPivot('price');
}
}
我想做的是获取有特定问题的特定手机的价格。
这就是我现在拥有的方式,但我觉得 Laravel 有一个内置的 Eloquent 功能,我无法以更简单的方式做到这一点:
$model = $this->phoneService->getModelFromSlug($model_slug);
$problem = $this->phoneService->getProblemFromSlug($problem_slug);
所有这些都是从他们的 slug 中选择特定的模型和问题。
然后我所做的就是使用这些凭据我得到这样的价格:
$row = DB::table('phone_model_phone_problem')
->where('phone_model_id', '=', $model->id)
->where('phone_problem', '=', $problem->id)
->first();
所以现在我可以得到像 $row->price 这样的价格,但我觉得需要一种更简单、更“Laravel”的方式来做到这一点。
【问题讨论】:
标签: php mysql laravel many-to-many pivot-table