[英]Laravel Eloquent join several tables
I have 3 tables: 我有3张桌子:
products
|id|name|about|
=categories=
|id|name|parent|
=products-categories=
|id|product_id|cat_id|
I need to take a product categories names. 我需要一个产品类别名称。 I have a sql query: 我有一个SQL查询:
SELECT s.name FROM products AS p
LEFT JOIN `products-categories` AS cats ON p.id = cats.product_id
LEFT JOIN `categories` AS s ON cats.cat_id = s.id
WHERE product_id = 1;
And It works! 而且有效! But how I can do this with the help of Laravel Eloquent (Not Fluent!) 但是我如何在Laravel Eloquent的帮助下做到这一点(不流利!)
You can use Eloquent
relationship and in this case, create two models, for both tables, ie product
and Category
: 您可以使用Eloquent
关系,在这种情况下,为两个表创建两个模型,即product
和Category
:
class Category extends Eloquent {
protected $table = 'categories'; // optional
public function products()
{
return $this->belongsToMany('Product', 'products_categories', 'category_id', 'product_id');
}
}
class Product extends Eloquent {
protected $table = 'products'; // optional
public function categories()
{
return $this->belongsToMany('Category', 'products_categories', 'product_id', 'category_id');
}
}
Now you may use these relationship methods to get related data, for example: 现在,您可以使用这些关系方法来获取相关数据,例如:
$product = Product::with('categories')->find(1);
This will return the product with id 1
and all the related categories in a collection so you may use $product->categories->first()->name
or you may do a loop on the categories like: 这将返回ID为1
的产品以及集合中所有相关类别,因此您可以使用$product->categories->first()->name
,也可以对以下类别进行循环:
foreach($product->categories as $cat) {
echo $cat->name;
}
Also you may use join
which doesn't require the relationship methods and you may use same approach to join the models that is used in Fluent
(Check other answer). 你也可以使用join
不需要的关系的方法和你可以使用同样的方法加入了在使用的模型Fluent
(检查其他答案)。 But either way, you need to store the category
and product
mappings in the products_categories
table. 但是,无论哪种方式,您都需要将category
和product
映射存储在products_categories
表中。 Read more about many-to-many
relationship on Laravel
website . 在Laravel
网站上了解有关many-to-many
关系的Laravel
信息 。
Just use the leftJoin
method. 只需使用leftJoin
方法。 It works the same in Eloquent as in Query Builder. 它在Eloquent中的工作原理与在Query Builder中相同。
$product = Product::leftJoin('product-categories', 'product-categories.product_id', '=', 'products.id')
->leftJoin('categories', 'categories.id', '=', 'product-categories.cat_id')
->where('product_id', 1)
->first(['categories.name']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.