![](/img/trans.png)
[英]How to create join query for multiple models with separate conditions in laravel Eloquent ORM
[英]How to make a multiple join query with Eloquent ORM
長話短說,如何使用 Eloquent ORM 方法執行下一個 MySql 查詢?
Ps:我想使用multiple join選項而不是我知道Eloquent ORM在幕后執行的多個選擇或子查詢,我不知道是否可能,以提高數據庫性能
select t.*,
d.name,
tt.name
from template t
inner join template_type tt on t.id_template_type = tt.id_template_type
inner join department d on t.id_department = d.id_department
inner join user_department ud on d.id_department = ud.id_department
inner join `user` u on ud.id_user = u.id_user
where u.id_user = 1;
模板表
| id_template | name | id_department | id_template_type | content |
|-------------|---------|---------------|------------------|---------------|
| 1 | temp 14 | 1 | 1 | some content |
| 2 | temp 25 | 2 | 3 | other content |
模板類型表
| id_template_type | name | active |
|------------------|------------|--------|
| 1 | my type | 1 |
| 2 | elses type | 1 |
部門表
| id_department | name | active |
|---------------|--------------|--------|
| 1 | my dept | 1 |
| 2 | another dept | 1 |
數據透視表部門用戶
| id_user_department | id_user | id_department |
|--------------------|---------|---------------|
| 1 | 2 | 1 |
| 2 | 6 | 2 |
| 3 | 6 | 3 |
用戶表
| id_user | name |
|---------|--------------|
| 1 | My User |
| 2 | Another User |
模板類
class Template extends Model
{
protected $primaryKey = 'id_template';
protected $table = 'template';
public function departments()
{
return $this->belongsTo(Department::class);
}
public function types()
{
return $this->belongsTo(TemplateType::class);
}
}
模板類型類
class TemplateType extends Model
{
protected $primaryKey = 'id_template_type';
protected $table = 'template_type';
public function templates()
{
$this->hasMany(Template::class, 'id_template_type', 'id_template_type');
}
}
系類
class Department extends Model
{
protected $table = 'department';
protected $primaryKey = 'id_department';
public function users()
{
return $this->belongsToMany(Users::class, 'user_department', 'id_department', 'id_user');
}
}
用戶類
class User extends Model
{
protected $table = 'user';
protected $primaryKey = 'id_user';
public function departments()
{
return $this->belongsToMany(Department::class, 'user_department', 'id_user', 'id_department');
}
}
如果你建立了正確的關系。 你可以這樣做:
$templates = Template::with('type', 'department')
->whereHas('department', function($query) use ($user_id) {
return $query->whereHas('users', function($user_query) use ($user_id) {
return $user_query->where('id', $id')
});
})
從部門的用戶應該是多對多這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.