我的模型中有这样的关系:
class Product extends Model
{
protected $fillable = [
'id', 'title', 'description', 'main_image', 'price', 'category_id', 'in_stock', 'ammount', 'status', 'quatable', 'images'
];
public function enabled_category()
{
return $this->belongsTo('App\Categories', 'category_id')->where('enabled', 'yes');
}
}我正在尝试获取属于已启用类别的产品,其中已启用==是
所以我是这样得到它们的:
$products = Product::with('enabled_category')->get();但我仍然得到了禁用类别的产品,其中categories.enabled == 'no‘
在我的phpdebugbar中,我只看到这两个查询被调用:
select * from `products`
select * from `categories` where `enabled` = 'yes' and `categories`.`id` in ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49')而且我仍然可以买到所有的产品,即使是那些残疾人类别的产品。
为什么会出现这种情况,以及如何获得只属于已启用类别的产品?
发布于 2017-02-16 02:44:20
它正在做你所要求的事情...
$products = Product::with('enabled_category')->get();你基本上是在告诉Eloquent,fetch all products和enabled_category关系。因此,它将加载所有的产品,因此
select * from `products`然后立即加载这些产品的关系( in列表是要加载关系的产品id,请注意where子句包含在其中,因此不会立即加载enabled=no,因为它应该...很好的优化,只有2个查询...)
select * from `categories` where `enabled` = 'yes' and `categories`.`id` in ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49')@NetGuy建议了一个简单的查询颠倒...这才是你真正想要的。
Category::where("enabled", "yes")->with("products")->get();您只需在您的类别中定义产品关系...
希望这能有所帮助
发布于 2017-02-16 03:04:09
根据Eloquent: Relationships中的文档,您将尝试直接在动态属性中查询结果。试着这样做:
在你的模型中
public function enabled_category() {return $this->belongsTo('App\Categories', 'category_id'); }然后在你的控制器中
类别::where(“enabled”,"yes")->with("products")->get();
它应该是有效的!
https://stackoverflow.com/questions/42253622
复制相似问题