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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26566675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:57:31  来源:igfitidea点击:

getting the value of an extra pivot table column laravel

phpmysqllaravelmany-to-manypivot-table

提问by Rodrigo

I have a phone_models, phone_problems, and a phone_model_phone_problem pivot table. The pivot table has an extra column 'price'.

我有一个 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');
    }
}

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->pricebut I feel like there needs to be a much easier and more 'Laravel' way to do this.

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

回答by lukasgeiter

When using Many to Many relationships with Eloquent, the resulting model automatically gets a pivotattribute 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:

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

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

回答by Yevgeniy Afanasyev

To getdata 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 updatedata in the pivot you can go 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 createnew:

创建新的:

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

It has been tested and proved working in Laravel 5.1 Read more.

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

回答by agm1984

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, Accountis your normal model, and you have $account->userswhich has the account_userjoin table with standard columns account_idand 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 模型,你就指示你的 Account 模型通过->using(AccountUserPivot::class).

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_byis 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”)