【发布时间】:2016-12-26 14:00:12
【问题描述】:
如何查询关系并仍然包含没有关系的模型?有两种型号
商店
产品
代码
// Store
public function products() {
$this->belongsToMany('App\Store');
}
// Product
public function stores() {
$this->belongsToMany('App\Product');
}
还有一个用于连接它们的数据透视表,称为product_store。有些商店没有任何产品。我如何查询所有产品,即使是那些不属于任何商店的产品,例如:
Product::where('store.id', '=', 1)->get()
这就是我目前的做法。
Product::whereHas('stores', function($query) {
$query->where('id', '=', $store_id);
});
但是作为laravel docs mention这个
检索至少有一个商店的所有产品
【问题讨论】: