Php 如何将where子句添加到Laravel关系?
这是我的模型:Php 如何将where子句添加到Laravel关系?,php,laravel,Php,Laravel,这是我的模型: namespace App; use Illuminate\Database\Eloquent\Model; class purchase_order extends Model { protected $table = "purchase_order"; public $timestamps = false; public function commodities() { return $this->hasMany(c
namespace App;
use Illuminate\Database\Eloquent\Model;
class purchase_order extends Model
{
protected $table = "purchase_order";
public $timestamps = false;
public function commodities()
{
return $this->hasMany(commodities::class, 'purchase_order_id', 'id');
}
}
现在我需要向
commodities()
方法添加一个条件。实际上,我需要说它返回商品
,其中包含where('productions.invoited',1)
。如何将where子句添加到关系中?最好的方法是将查询范围invoinced()
添加到商品
模型中
因此,在您的商品
模型上,您可以添加:
public function scopeInvoiced($query){
return $query->where('invoiced', 1);
}
然后用
商品->发票()调用此函数代码>您可以这样做,但请参考关系表,如下所示:
public function commodities()
{
return $this->hasMany(commodities::class, 'purchase_order_id', 'id')
->where('commodities.invoiced', 1);
}
在构建查询时,它会考虑商品。发票
以及where查询
参考:目前我使用它的方式是采购订单::with(“商品”)
。在您的情况下,如何使用with
?$purchase\u orders=purchase\u order::with(['productions'=>函数($query){$query->invoinced();}]);创建一个调用invoinced()
的不同关系,或者按照@Davit所说的内联执行。那么invoinced()
函数定义在哪里?@MartinAJinvoinced()
是您的范围,它将命中scopeinvoinced()
函数,可以在提供的链接中阅读更多内容