簡體   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