Home >Backend Development >PHP Tutorial >Laravel multi-table association query problem
Product list(product)
Package
Package information table (package_data).
id(self-incremented id)
name
...
id(self-incremented id)
title (package name)
....
id(self-incremented id)
product_id (product id)
package-id(package id)
product_num (number of products)
...
There are multiple products in a package. The package table and package information table could have been placed in one table. However, in order to reduce redundant data, the package table was simply divided vertically.
In the above situation, I want to know how many products A are included in package A. So how to define the relationships in the model?
In the above situation, I want to know how many products A, product B, etc... are used in package A and package B. So how to operate?
ps: The above questions have been read through the official documents, but my IQ is too low, which leads to unclear understanding, so I am here to ask you for advice.
Product list(product)
Package
Package information table (package_data).
id(self-incremented id)
name
...
id(self-incremented id)
title (package name)
....
id(self-incremented id)
product_id (product id)
package-id(package id)
product_num (number of products)
...
There are multiple products in a package. The package table and package information table could have been placed in one table. However, in order to reduce redundant data, the package table was simply divided vertically.
In the above situation, I want to know how many products A are included in package A. So how to define the relationships in the model?
In the above situation, I want to know how many products A, product B, etc... are used in package A and package B. So how to operate?
ps: The above questions have been read through the official documents, but my IQ is too low, which leads to unclear understanding, so I am here to ask you for advice.
Ahem~, I finally found the answer in the document. Link here . Please search for the "Nested eager loading" section to view it yourself.
Tell me the specific process:
<code class="php">public function hasManyData() { return $this->hasMany(PackageData::class, 'package_id', 'id'); }</code>
<code class="php">public function BelongsToProduct() { return $this->belongsTo(Product::class, 'product_id', 'id'); }</code>
<code class="php">$packageList = Package::with('hasManyData', 'package_data.BelongsToProduct')->get();</code>
Done!
ps: The method given by a colleague is roughly like this. The following is the pseudo code:
<code class="php">$packageList = Package::with('hasManyData')->get(); foreach( $packageList as $key => $val ) { ... $productList = PackageData::with('BelongsToProduct')->where(...)->get(); ... }</code>
I think the performance is terrible~ and I don’t want to study it anymore! My head is a bit hot, so what I wrote is a bit messy. Please correct me if I am wrong. Thank you to everyone who has watched this issue~