Reputation: 1073
If I am not right, please correct me.
There is table products
and categories
.
Each product has own category. So, it can be more that one.
So, no I need to select all products by specified category.
What kind of relation I should use in model: belongsTo
, or hasMany
?
Is it important sequence?
Upvotes: 0
Views: 161
Reputation: 20486
Since products
have multiple categories
and categories
can have multiple products
, this is known as a many-to-many SQL relationship.
If we go to the Laravel Eloquent documentation, you'll see that you want to use belongsToMany()
. This means, if you want to be able to retrieve all of your products
from a category
, you would do something like this (shamelessly copied from Laravel's documentation):
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
/**
* The products that belong to the category.
*/
public function products()
{
return $this->belongsToMany('App\Product');
}
}
And, of course the other side of this many-to-many relationship is very similar:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
/**
* The categories that belong to the product.
*/
public function categories()
{
return $this->belongsToMany('App\Category');
}
}
Now...if you want to fetch all products and subsequently find all categories for each product, you would do something like this:
$products = Product::all();
foreach($products as $product) {
// var_dump($product);
$categories = $product->categories();
foreach($categories as $category) {
// var_dump($category);
}
}
Upvotes: 2