繁体   English   中英

Laravel-雄辩的3表查询

[英]Laravel - Eloquent 3 Table Query

我知道关于3个表联接有几个问题,但是示例比我的设置要简单。

我有三个表: ItemsAttributesCategories

`item.item_code = attributes.item_code`

`attributes.category_id = category.id`

用雄辩的话,我可以访问属性没有问题:

$ items = Item :: with('attributes')-> paginate(15);

但是我似乎无法正确设置关系以检索类别名称。

对于标准的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

我该如何运用雄辩的语言实现这一目标?

编辑-我的糟糕-完全搞砸了SQL。 更新以反映正确的表名称并包括第二个联接

更新资料

我的模型当前如下所示:

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);
    }
}

但这仍然没有返回结果。 我试过使用

$items = Item::with('attributes.category')->get();

如建议的那样,但这仍然会引发错误。 如果我将产品模型更新为:

class Product extends Model
{
    public function item()
    {
        return $this->belongsTo(Item::class);
    }
    public function category(){

        return $this->belongsTo(Category::class);
    }

}

我没有收到错误,但是关系返回null。

你可以做

$items = Item::with('attributes.category')->get();

因此,您可以在attributes关系内访问category关系。

例如:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM