[英]Laravel - Eloquent 3 Table Query
I know there are several questions out there on 3 table joins, but the examples are simpler than my set up. 我知道关于3个表联接有几个问题,但是示例比我的设置要简单。
I have three tables: Items
, Attributes
, Categories
. 我有三个表:
Items
, Attributes
, Categories
。
`item.item_code = attributes.item_code`
`attributes.category_id = category.id`
Using eloquent, I can access attributes no problem with: 用雄辩的话,我可以访问属性没有问题:
$items = Item::with('attributes')->paginate(15); $ items = Item :: with('attributes')-> paginate(15);
But I can't seem to get the relationship set correctly to retrieve the category name. 但是我似乎无法正确设置关系以检索类别名称。
With a standard MySql query I'd use something like: 对于标准的MySql查询,我将使用类似以下内容:
SELECT category_name FROM items
JOIN attributes on items.item_code = attributes.item_code
JOIN categories on attributes.pg3_id = categories.id
WHERE items.item_code = 40992264
How do I achieve this using eloquent? 我该如何运用雄辩的语言实现这一目标?
Edit - My bad - Totally messed up the SQL. 编辑-我的糟糕-完全搞砸了SQL。 Updated to reflect the correct table names and include the second join
更新以反映正确的表名称并包括第二个联接
Update 更新资料
My models currently look like this: 我的模型当前如下所示:
class Attributes extends Model
{
public function category(){
return $this->belongsTo(Category::class);
}
}
class Product extends Model
{
public function item()
{
return $this->belongsTo(Item::class);
}
}
class Category extends Model
{
public function attributes()
{
return $this->belongsTo(Attributes::class);
}
}
But this still isn't returning a result. 但这仍然没有返回结果。 I've tried using
我试过使用
$items = Item::with('attributes.category')->get();
as suggested, but this still throws an error. 如建议的那样,但这仍然会引发错误。 If I update the Product model to:
如果我将产品模型更新为:
class Product extends Model
{
public function item()
{
return $this->belongsTo(Item::class);
}
public function category(){
return $this->belongsTo(Category::class);
}
}
I don't get an error, but the relationship returns null. 我没有收到错误,但是关系返回null。
You can do 你可以做
$items = Item::with('attributes.category')->get();
So you access the category
relationship inside the attributes
relationship. 因此,您可以在
attributes
关系内访问category
关系。
For example: 例如:
foreach ($items as $item) {
foreach ($item->attributes as $attribute) {
echo $attribute->category->id; // Will print the category id.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.