programing

getting the value of an extra pivot table column laravel

sourcetip 2021. 1. 17. 12:38
반응형

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. 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:

$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.

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.


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

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.

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:

$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.

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.

ReferenceURL : https://stackoverflow.com/questions/26566675/getting-the-value-of-an-extra-pivot-table-column-laravel

반응형