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()
函数定义在哪里?@MartinAJ
invoinced()
是您的范围,它将命中
scopeinvoinced()
函数,可以在提供的链接中阅读更多内容