我正在使用Laravel及其提供的Eloquent ORM,但我一直在努力选择所需的数据。我有2个模型
Company
Member
我该怎么做?
SELECT * FROM members m, companies c
WHERE (m.main_type = "2" AND m.main_id = c.id AND m.status = "1")
AND ((m.username LIKE "%keywords%") OR (c.name LIKE "%keywords%"))
答案 0 :(得分:1)
考虑公司可以有多个成员,您需要先拥有以下关系:
Company
型号:
public function members(){
return $this->hasMany(Member::class);
}
Member
型号:
public function company(){
return $this->belongsTo(Company::class,'main_id');
}
然后您可以使用关系来获取数据:
$result = Company::with(['members' => function($q){
return $q->where('main_type', 2)->where('status', 1)->where(function($sq){
return $sq->where('username', 'like', '%keywords%')
->orWhere('name', 'like', '%keywords%');
});
}]);
A会根据您的外键名称来更新关系。我建议保持member_id
或company_id
答案 1 :(得分:0)
它应该看起来像这样。您不需要子查询。
Member::join('companies', 'companies.id', '=', 'members.main_id')
->where(function($query) {
$query->where('main_type', 2)->where('status', 1);
})->where(function($query) {
$query->where('username', 'like', '%keywords%')->orWhere('name', 'like', '%keywords%');
});