简体   繁体   English

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

[英]getting the value of an extra pivot table column laravel

I have a phone_models, phone_problems, and a phone_model_phone_problem pivot table.我有一个 phone_models、phone_problems 和一个 phone_model_phone_problem 数据透视表。 The pivot table has an extra column 'price'.数据透视表有一个额外的列“价格”。

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

What I'm trying to do is get the price of a specific phone with a specific problem.我想要做的是获得具有特定问题的特定手机的价格。

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:这就是我现在的方式,但我觉得 Laravel 有一个内置的 Eloquent 功能,我找不到以更简单的方式做到这一点:

$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.所有这些都是从他们的 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();

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

When using Many to Many relationships with Eloquent, the resulting model automatically gets a pivot attribute assigned.在 Eloquent 中使用多对多关系时,生成的模型会自动分配一个pivot属性。 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');

Official Docs 官方文档

If you need more help the task of configuring the relationships with Eloquent, let me know.如果您需要更多帮助来配置与 Eloquent 的关系,请告诉我。

Edit编辑

To query the price do this要查询价格,请执行此操作

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

To get data from pivot table:数据透视表获取数据:

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

Or if you have many records with different price:或者,如果您有许多不同价格的记录:

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

In addition.此外。

To update data in the pivot you can go NEW WAY :更新数据透视中的数据,您可以采用NEW WAY

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

Where the 2nd param is set to false meaning that you don't detach all the other related models.其中第二个参数设置为 false 意味着您不会分离所有其他相关模型。

Or, go old way或者,走老路

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

And remind you:并提醒您:

To delete :删除

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

To create new:创建新的:

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

It has been tested and proved working in Laravel 5.1 Read more.它已经过测试并证明可以在 Laravel 5.1 中工作阅读更多。

Laravel 5.8~ Laravel 5.8~

If you want to make a custom pivot model, you can do this:如果要制作自定义枢轴模型,可以执行以下操作:

Account.php帐号.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'
            );
    }
}

AccountUserPivot.php AccountUserPivot.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;
    }
}

In the above example, Account is your normal model, and you have $account->users which has the account_user join table with standard columns account_id and user_id .在上面的示例中, Account是您的普通模型,您有$account->users ,其中包含account_user连接表,其中包含标准列account_iduser_id

If you make a custom pivot model, you can add attributes and mutators onto the relationship's columns.如果您制作自定义数据透视模型,您可以将属性和修改器添加到关系的列中。 In the above example, once you make the AccountUserPivot model, you instruct your Account model to use it via ->using(AccountUserPivot::class) .在上面的例子中,一旦你创建了 AccountUserPivot 模型,你就可以通过->using(AccountUserPivot::class)指示你的 Account 模型使用它。

Then you can access everything shown in the other answers here, but you can also access the example attribute via $account->user[0]->pivot->status_updated_by_nice (assuming that status_updated_by is a foreign key to an ID in the users table).然后您可以访问此处其他答案中显示的所有内容,但您也可以通过$account->user[0]->pivot->status_updated_by_nice访问示例属性(假设status_updated_by是用户表中 ID 的外键)。

For more docs, see https://laravel.com/docs/5.8/eloquent-relationships (and I recommend press CTRL+F and search for "pivot")有关更多文档,请参阅https://laravel.com/docs/5.8/eloquent-relationships (我建议按 CTRL+F 并搜索“pivot”)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM