[英]Exclude records which have relation empty/null in Illuminate Eloquent ORM outside laravel
狀態 - 已解決
我在 laravel 之外使用Illuminate ORM 。 所以,到目前為止工作良好,但我在關系上遇到了麻煩。 我想排除那些profile和accountDetails關系為空或null 的記錄。 目前我手動提取這些字段並創建另一個數組並返回它,但它有很多處理,所以如果它為空或為空,我有什么方法可以為關系設置一些條件排除這些記錄。
這是我的代碼
$users = \App\User::where('account_type_id', 2)
->with('profile', 'accountDetails')
->get()
->toArray();
在User Model 中,我創建了兩個關系,即。 個人資料和帳戶詳細信息
public function profile()
{
return $this->hasOne('\App\UserProfile', 'user_id', 'id');
}
public function accountDetails()
{
return $this->hasMany('\App\Wallet', 'user_id', 'id');
}
提前致謝。 :)
請對此提供任何幫助。
一種方法是使用連接機制。
$users = \App\User::join('profile','profile.user_id','=','user.id')
->join('wallet','wallet.user_id','=','user.id')
->where([
['user.account_type_id','=',2],
['profile.id','=',null],
['wallet.id','=',null]
])
->get()
->toArray();
加入: https : //laravel.com/docs/5.2/queries#joins
第二種方法,使用雄辯的關系,
在用戶模型上:
public function profile() {
return $this->hasOne('\App\UserProfile', 'user_id', 'id');
}
public function accountDetails(){
return $this->hasMany('\App\Wallet', 'user_id', 'id');
}
然后查詢:
$users = \App\User::where('account_type_id', 2)
->has('profile')
->has('accountDetails')
->get()
->toArray();
has
查詢方法: https : //laravel.com/docs/5.2/eloquent-relationships#querying-relations
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.