我想用where条件来过滤我的查询。假设我有一个产品模型,这个模型与买家模型有关系。我想得到从一组买家那里购买的产品模型列表,其中买家是65岁及以上。
$query = Product::with('Buyer')
->where('Buyer.age','>=',65)
->get();
但是,我不能像这样放置where条件,它显示 "未知列Buyer.age"。请教我如何过滤我的结果?
试试这个。
$query = Product::with('Buyer')
->whereHas('Buyer', function($q){ // whereHas will only return products whose buyer is >= 65
$q->where('age','>=',65);
})
->get();
请试一试。
$query = Product::whereHas('Buyer', function ($query) {
$query->where('age', '>=', 65);
})->with(['Buyer' => function($q){
$q->where('age','>=',65);
}])
->get();