如何在Laravel关系中添加where子句?

时间:2018-07-05 09:07:46

标签: php laravel

这是我的模特:

SELECT "fields_count" / SUM("fields_count") AS not_able_to_use_SUM_with_field , "error" FROM ( 
    SELECT COUNT("some_unique_data") AS fields_count AS fields_sum FROM "my_measument" WHERE $timeFilter GROUP BY "error"
)

现在,我需要向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()并返回commodities。如何将此where子句添加到关系中?

2 个答案:

答案 0 :(得分:2)

最好的方法是将invoiced()的查询范围添加到您的Commodities模型中。

https://laravel.com/docs/5.6/eloquent#query-scopes

因此,在您的Commodities模型上,您可以添加:

public function scopeInvoiced($query){
    return $query->where('invoiced', 1);
}

然后使用Commodities->invoiced();

答案 1 :(得分:0)

您可以执行此操作,但可以参考关系表,如下所示:

public function commodities()
{
    return $this->hasMany(commodities::class, 'purchase_order_id', 'id')
        ->where('commodities.invoiced', 1);
}

构建查询时,它也会在commodities.invoiced处进行查询

参考:https://laraveldaily.com/filter-eloquent-relationships-fly-need/