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

getting the value of an extra pivot table column laravel

提问人:Rodrigo 提问时间:10/26/2014 最后编辑:Rodrigo 更新时间:12/13/2019 访问量:125655

问:

我有一个phone_models、phone_problems和一个phone_model_phone_problem数据透视表。数据透视表有一个额外的列“price”。

电话型号:

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

所有这一切都是从他们的蛞蝓中选择特定的模型和问题。

然后我所做的就是使用这些凭据,我得到的价格是这样的:

$row = DB::table('phone_model_phone_problem')
->where('phone_model_id', '=', $model->id)
->where('phone_problem', '=', $problem->id)
->first();

所以现在我可以得到这样的价格,但我觉得需要有一种更简单、更“Laravel”的方式来做到这一点。$row->price

php mysql laravel 对多 数据透视表

评论


答:

178赞 lukasgeiter 10/26/2014 #1

将多对多关系与 Eloquent 一起使用时,生成的模型会自动分配一个属性。通过该属性,您可以访问数据透视表列。 尽管默认情况下,透视对象中只有键。若要将列也放在那里,需要在定义关系时指定它们:pivot

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

官方文档

如果您在配置与 Eloquent 的关系的任务中需要更多帮助,请告诉我。

编辑

要查询价格,请执行以下操作

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

评论

0赞 Brent Connor 9/1/2015
有人可以展示如何基于额外的列查询数据透视表,例如上面的这个例子price$model->problems()->where('phone_problem', $problem->id)->first()->pivot->price
0赞 Bartu 12/27/2015
不获取而是设置该枢轴条目的值(如价格)怎么样?
0赞 lukasgeiter 12/28/2015
@Bartu这应该有效: .如果没有,请提出一个新问题,因为评论并不是真正适合的地方。$model->problems()->updateExistingPivot($problemId, ['price' => $newPrice])
0赞 Bartu 12/28/2015
它有效,也许您可以添加它以供其他人进一步参考。
24赞 Yevgeniy Afanasyev 1/12/2016 #2

要从数据透视表中获取数据,请执行以下操作:

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

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

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

另外。

更新透视中的数据,您可以采用新方式

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

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

或者,走老路

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

并提醒您:

要删除

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

创建新的:

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

它已经过测试并证明可以在 Laravel 5.1 中工作 阅读更多。

评论

3赞 Dim13i 4/11/2018
理想情况下,更新它仍然更好使用 .此外,在 Laravel 5.6 中,可以使用该函数,而不是作为第二个参数传递给 。updateExistingPivot()falsesync()syncWithoutDetaching()
5赞 agm1984 12/13/2019 #3

拉拉维尔 5.8~

如果要创建自定义透视模型,可以执行以下操作:

帐户 .php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Account extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class)
            ->using(AccountUserPivot::class)
            ->withPivot(
                'status',
                'status_updated_at',
                'status_updated_by',
                'role'
            );
    }
}

帐户用户透视.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;

class AccountUserPivot extends Pivot
{
    protected $appends = [
        'status_updated_by_nice',
    ];

    public function getStatusUpdatedByNiceAttribute()
    {
        $user = User::find($this->status_updated_by);

        if (!$user) return 'n/a';

        return $user->name;
    }
}

在上面的示例中,是您的普通模型,并且您具有具有标准列和 .Account$account->usersaccount_useraccount_iduser_id

如果创建自定义透视模型,则可以将属性和赋值器添加到关系的列中。在上面的示例中,创建 AccountUserPivot 模型后,通过 指示 Account 模型使用它。->using(AccountUserPivot::class)

然后,您可以访问此处其他答案中显示的所有内容,但您也可以通过以下方式访问示例属性(假设这是 users 表中 ID 的外键)。$account->user[0]->pivot->status_updated_by_nicestatus_updated_by

有关更多文档,请参阅 https://laravel.com/docs/5.8/eloquent-relationships(我建议按 CTRL+F 并搜索“pivot”)