Laravel: Add a join to self referencing Many-to-Many relationship?

mOrloff

We have a self referencing product-to-product relationship, and I am struggling to return data based on another FK in the pivot table.

I'm playing with a sample pivot table that looks like this:
tmp_prod2prod:

  • id
  • prod_id_to
  • prod_id_from
  • affiliation_type_id

And that affiliation_type_id FK refers to this table:
affiliation_types:

  • id
  • type
  • description

(BTW, if you want to see a full schema, find it here on pastebin)

GOAL:
My goal is to show affiliation_types.type.

My model looks like:

class TmpProd extends Eloquent {

    protected $table = 'tmp_prods';
    public $timestamps = false;


    public function affiliatedToProducts()
    {
        return $this->belongsToMany('TmpProd', 'tmp_prod2prod', 'p_id_to', 'p_id_from')
            ->withPivot('affiliation_type_id')
            ->join('affiliation_types', 'tmp_prod2prod.affiliation_type_id', '=', 'affiliation_types.id');
    }

    public function affiliatedFromProducts()
    {
        return $this->belongsToMany('TmpProd', 'tmp_prod2prod', 'p_id_from', 'p_id_to');
    }

}

and my controller I'm running:

    $model = TmpProd::find(1);
    foreach ($model->affiliatedToProducts as $cross) {
        echo"<pre>",var_dump($cross->pivot),"</pre>\n";
    }

I've tried enough variations that I feel like my head is spinning :)
How do I reconcile the affiliation_types.type based on the affiliation_type_id FK in the pivot table?

damiani

After going round and round with custom pivot models, all sorts of convoluted relations, etc., I believe I've found a simple solution—just add a select statement to your relation, targeting the affiliation_types table, so that you have access to the types column:

return $this->belongsToMany('TmpProd', 'tmp_prod2prod', 'p_id_to', 'p_id_from')
    ->withPivot('affiliation_type_id')
    ->join('affiliation_types', 'tmp_prod2prod.affiliation_type_id', '=', 'affiliation_types.id')
    ->addSelect('affiliation_types.type as affiliation_type');

(The as affiliation_type part is optional, but will make your query clearer semantically.)

Then, in your foreach loop, you can call:

var_dump($cross->affiliation_type);

It would also be a good idea to eager-load your affiliatedToProducts relations, to reduce the number of queries from N+1 down to 2. So, to find a particular product by ID:

$model = TmpProd::with('affiliatedToProducts')->find(1);

Or, if you need to retrieve all products:

$model = TmpProd::with('affiliatedToProducts')->get();

...then loop over the results with foreach ($model as $m).


Update: This worked for Laraval v4.2.8, but as of v4.2.11, it seems (counterintuitively) that ->addSelect replaces, rather than adds, the query's original select statement, and is functionally identical to just using ->select. So for versions newer than 4.2.8, it is necessary to add the original table back into the query, so the belongsToMany relation should end with:

->select('affiliation_types.type', 'tmp_prods.*');

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Self referencing one to many Model

分類Dev

View Many to Many Relationship in laravel

分類Dev

Doctrine's Many-To-Many Self-Referencing and reciprocity

分類Dev

How to diff and intersect Many-To-Many Self-referencing ArrayCollections

分類Dev

Laravel save / update many to many relationship

分類Dev

Friendship system with Laravel : Many to Many relationship

分類Dev

Laravel One to Many of One to Many relationship

分類Dev

How can I make a Many to many relation on same table (many to many Join To Self)

分類Dev

Add additional column to existing many to many relationship - EF Code First

分類Dev

Laravel fetch only pivot columns in many to many relationship

分類Dev

Laravel, pivot table conflicts with many-to-many relationship

分類Dev

Laravel 5.5 Update a checkbox of many to many relationship model

分類Dev

Synchronizing a one-to-many relationship in Laravel

分類Dev

How to insert a one to many relationship in Laravel

分類Dev

Laravel 5 Eloquent Relationship - Has Many Though

分類Dev

Many to many relationship CRUD in Room

分類Dev

Many-to-many relationship as list

分類Dev

backward filter and many to many relationship

分類Dev

Power Pivot Many to Many Relationship

分類Dev

Querying a many to many relationship in SQL

分類Dev

How to perform reduce side join on Java Mapreduce with two table which have many-to-many relationship?

分類Dev

Convert existing many to many to reverse many to many relationship using XSLT

分類Dev

Creating one to many relationship with pivot table of many to many relationship

分類Dev

Laravel Eloquent Eager Loading Multiple Has Many Relationship

分類Dev

How to eager load only 1 result from many to many relationship Laravel

分類Dev

How to handle Many to Many relationship in mongoDB?

分類Dev

SQL: many-to-many relationship and the 'ALL' clause

分類Dev

Postgres many to many relationship on same base table

分類Dev

Many to many relationship with cascade or set null delete?

Related 関連記事

  1. 1

    Self referencing one to many Model

  2. 2

    View Many to Many Relationship in laravel

  3. 3

    Doctrine's Many-To-Many Self-Referencing and reciprocity

  4. 4

    How to diff and intersect Many-To-Many Self-referencing ArrayCollections

  5. 5

    Laravel save / update many to many relationship

  6. 6

    Friendship system with Laravel : Many to Many relationship

  7. 7

    Laravel One to Many of One to Many relationship

  8. 8

    How can I make a Many to many relation on same table (many to many Join To Self)

  9. 9

    Add additional column to existing many to many relationship - EF Code First

  10. 10

    Laravel fetch only pivot columns in many to many relationship

  11. 11

    Laravel, pivot table conflicts with many-to-many relationship

  12. 12

    Laravel 5.5 Update a checkbox of many to many relationship model

  13. 13

    Synchronizing a one-to-many relationship in Laravel

  14. 14

    How to insert a one to many relationship in Laravel

  15. 15

    Laravel 5 Eloquent Relationship - Has Many Though

  16. 16

    Many to many relationship CRUD in Room

  17. 17

    Many-to-many relationship as list

  18. 18

    backward filter and many to many relationship

  19. 19

    Power Pivot Many to Many Relationship

  20. 20

    Querying a many to many relationship in SQL

  21. 21

    How to perform reduce side join on Java Mapreduce with two table which have many-to-many relationship?

  22. 22

    Convert existing many to many to reverse many to many relationship using XSLT

  23. 23

    Creating one to many relationship with pivot table of many to many relationship

  24. 24

    Laravel Eloquent Eager Loading Multiple Has Many Relationship

  25. 25

    How to eager load only 1 result from many to many relationship Laravel

  26. 26

    How to handle Many to Many relationship in mongoDB?

  27. 27

    SQL: many-to-many relationship and the 'ALL' clause

  28. 28

    Postgres many to many relationship on same base table

  29. 29

    Many to many relationship with cascade or set null delete?

ホットタグ

アーカイブ