首页 文章

获取额外的数据透视表列laravel的值

提问于
浏览
42

我有一个phone_models,phone_problems和一个phone_model_phone_problem数据透视表 . 数据透视表有一个额外的列“价格” .

PhoneModel:

class PhoneModel extends \Eloquent
{
    public function problems()
    {
        return $this->belongsToMany('RL\Phones\Entities\PhoneProblem')->withPivot('price');
    }
}

PhoneProblem:

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'方式来做到这一点 .

2 回答

  • 85

    从数据透视表到 get 数据:

    $price = $model->problems()->findOrFail($problem->id, ['phone_problem'])->pivot->price;
    

    或者,如果您有许多不同价格的记录:

    $price = $model->problems()->where('phone_problem', $problem->id)->firstOrFail()->pivot->price;
    

    In addition.

    要在数据透视中的 update 数据,您可以去 NEW WAY

    $model->problems()->sync([$problemId => [ 'price' => $newPrice] ], false);
    

    第二个参数设置为false意味着您不会分离所有其他相关模型 .

    或者,去 old way

    $model->problems()->updateExistingPivot($problemId, ['price' => $newPrice]);
    

    并提醒你:

    delete

    $model->problems()->detach($problemId);
    

    create 新:

    $model->problems()->attach($problemId, ['price' => 22]);
    

    它经过测试并证明在Laravel 5.1中工作Read more.

  • 9

    当使用与Eloquent的多对多关系时,生成的模型会自动获得分配的 pivot 属性 . 通过该属性,您可以访问数据透视表列 . 虽然默认情况下只有pivot对象中的键 . 要将列添加到那里,您需要在定义关系时指定它们:

    return $this->belongsToMany('Role')->withPivot('foo', 'bar');
    

    Official Docs

    如果您需要更多帮助来配置与Eloquent的关系,请告诉我 .

    Edit

    要查询价格,请执行此操作

    $model->problems()->where('phone_problem', $problem->id)->first()->pivot->price
    

相关问题