我用我的雄辩的查询生成器过滤数据时遇到了一些问题。我有事务模型和状态模型。该事务具有多个状态。我想得到hasMany关系的第一个数组并放在哪里。这是我的密码。
$var = Transaction::with([
'status' => function ($q) {
return $q->first();
}
])->whereHas('status',function ($x){
return $x->where('status',0);
})->get();
状态的模型是
public function status(){
return $this->hasMany('AppModelsStatus','transaction_id','id')->orderBy('status','desc');
}
结果仍然没有给我正确的数据。它应该通过返回第一个数组状态值为0 的数据
您可以使用hasOne关系构建一个新关系,然后加载它:
public function firstStatus(){
return $this->hasOne('AppModelsStatus','transaction_id','id')->orderBy('status','desc')->where('status',0); // or mybe just ' ->latest() to get the most recent one.
}
然后,您可以使用以下关系式:
$var = Transaction::with(['firstStatus'])->whereHas('status',function ($x){
return $x->where('status',0);
})->get();
这个加载关系将是第一个。
您可以为此创建另一个函数或更改现有函数
public function firstStatus() {
return $this->hasMany('AppModelsStatus','transaction_id','id')->orderBy('status','desc')->limit(1);
}
因为OMR,我终于可以算出了
首先,我必须像OMR一样设置模型,比如:
public function firstStatus(){
return $this->hasOne('AppModelsStatus','transaction_id','id')->orderBy('status','desc'); // or mybe just ' ->latest() to get the most recent one.
}
并将控制器放置为:
$var = Transaction::with(['firstStatus' => function($q){
return $q->where('status',0);
}])->whereHas('status',function ($x){
return $x->where('status',0);
})->get();
感谢OMR