2017-03-01 108 views
0

的專欄中,我有三個表:雄辯指相關的模型

categories 
id, title 

products 
id, name 

categories_products 
id, category_id, product_id 

我還設置了根據模型和關係(包括有其他的belongsToMany)

現在我想獲得屬於一個類別

Category::where('title','Electronics')->first()->products()->limit(10)->get(['products.name']); 

的正常工作的所有產品,但我也希望包括每個產品的類別標題,以及:

Category::where('title','Electronics')->first()->products()->limit(10)->get(['products.name','category.title']); 

但是它返回:列未找到category.title

我認爲關係會照顧它。

編輯:型號 - >

類別:

class Category extends Model 
{ 

    protected $fillable = array('title'); 

    public function products() 
    { 
     return $this->belongsToMany('Product', 'categories_products', 'category_id', 'product_id'); 
    } 
} 

class Product extends Model 
{ 

    protected $fillable = array('name'); 

    public function categories() 
    { 
     return $this->belongsToMany('Category', 'categories_products', 'product_id', 'category_id'); 
    } 
} 
+0

您可以張貼在每個模型的關係:

$category = Category::where('title','Electronics') ->with(['products' => function($query) { return $query->select('id', 'name')->limit(10); }]) ->first(['id', 'title']); 

然後訪問該產品? –

+0

看起來你在'categories'上引用'name',但name是在'products'上? –

+0

@EricTucker添加並修復了 – Chris

回答

1

你得到錯誤的原因是因爲get()作品就像select()因爲你正在運行的類別查詢,然後運行產品查詢之後沒有可供選擇的參考類別表。

調查Eager Loading。這將有助於解決很多這類問題。因爲我們是延遲加載,你需要在每個模型的id列,因此Laravel知道附着到哪裏的關係的查詢運行後

Product::select('id', 'name') 
->with(['categories' => function($query) { 
    return $query->select('id', 'title'); 
}]) 
->whereHas('categories', function($query) { 
    return $query->where('title', 'Electronics'); 
}) 
->limit(10) 
->get(); 

:您的查詢可以寫成。

上面的with()方法將迫切加載categories關係,並且whereHas()方法對當前查詢設置關係約束。

UPDATE

Category模型類似的查詢:

$category->products 
+0

重要的是帶有with功能的查詢。從Category :: – Chris

+0

Ahhh開始整個查詢時,它甚至可以更加整齊,更新了類別查詢的答案,而不是如果這就是您要查找的內容 –