hiddenicon
hiddenicon

Reputation: 581

Laravel Eloquent Model with multiple IDs

I will have a table that is full of information that involves other tables (relations). Most of the information in this table will only have the ID's of the referencing related table. If I were to use "products" as an example for this table it may look like this for some of the columns:

id  |  name  |  type_id  |  price_id  |  location_id  |  sale_id
----------------------------------------------------------------
 1  |  prod1 |     1     |      1     |       2       |     4
 2  |  prod2 |     2     |      1     |       1       |     1
 3  |  prod3 |     3     |      2     |       6       |     2
 4  |  prod4 |     1     |      2     |       3       |     4

I'm trying to take this "products" table and dump it out into a list. I would need to look up all of the items in these columns as I dump it out (the relation). I know how to do belongsToMany and hasMany, but I'm not sure how I can do this in one shot with an Eloquent model if I have a "products" model? Should I just make the products table just a pivot table? Can I do it with an Eloquent model or should I use query builder directly? I think if I were to use withPivot it would return the extra columns but the raw ID value from the column. I would need the value lookup from their respective table (the relation).

Tried something like this:

public function productItems(){
  return $this->belongsToMany(Product::class)->withPivot(["type_id","price_id",...]);
}

Upvotes: 1

Views: 1416

Answers (1)

Brian Lee
Brian Lee

Reputation: 18187

As suggested by @BagusTesa, you should eager load your relations:

$products = Product::with(['type', 'price', 'location'])->get();

That will query for the related models allowing you to access them as model properties:

foreach ($products as $product){
    // $product->type;
    // $product->price;
    // $product->location;
}

Upvotes: 0

Related Questions