[英]How to write a inner join in Eloquent ORM in laravel?
I have a tables named buildings
and flats
我有一张叫buildings
和flats
的桌子
buildings table 建筑物表
Building_Id | Building_Name | .......| Building_Owned_By | ....
flats table 单位表
Flat_Id | Flat_Name | ........| Fk_Building_Id | .....
and in My Models 和在我的模型中
Building 建造
class Building extends Eloquent {
protected $primaryKey = "Building_Id";
protected $table = 'buildings';
.......
.......
public function flat()
{
return $this->hasMany('Flat', 'Fk_Building_Id', 'Building_Id');
}
}
Flat 平面
class Flat extends Eloquent {
protected $primaryKey = "Flat_Id";
protected $table = 'flats';
.......
.......
public function building() {
return $this->belongsTo('Building','Fk_Building_Id', 'Building_Id');
}
}
and in my controller 在我的控制器中
$flats = Flat::where('Fk_Building_Id', '=',$buildingid)
->where('Building_Owned_By', '=',Auth::user()->Login_Id)
->orderBy('Flat_Name')
->get(array('Flat_Id as flatId', 'Flat_Name as flatName'))
->toArray();
But it returns nothing. 但是它什么也没返回。
How can we perform inner joins in Eloquent Orm (I dont want to use fluent query)? 我们如何在雄辩的Orm中执行内部联接(我不想使用流利的查询)?
Update 更新资料
Thanks for @Creator for his valuable time and help. 感谢@Creator的宝贵时间和帮助。 He helps me a lot for finding this. 他为我找到了很多帮助。 The solution is we have to use whereHas and we rewrite the code as 解决方案是我们必须使用whereHas,然后将代码重写为
$flats = Flat::whereHas('building', function($q){
$q->where('Building_Owned_By', '=',Auth::user()->Login_Id);
})
->where('Fk_Building_Id', '=',$buildingid)
->orderBy('Flat_Name')
->get(array('Flat_Id as flatId', 'Flat_Name as flatName'))
->toArray();
Do this : 做这个 :
class Building extends Eloquent {
protected $primaryKey = "Building_Id";
protected $table = 'buildings';
.......
.......
public function flat()
{
return $this->HasMany('Flat', 'Fk_Building_Id', 'Building_Id');
}
} }
Query to get building with all flats: 查询以获取所有单位的建筑物:
Building::with('flat')->(some_condition)->get();
class Flat extends Eloquent {
protected $primaryKey = "Flat_Id";
protected $table = 'flats';
.......
.......
public function building() {
return $this->HasOne('Building','Fk_Building_Id', 'Building_Id');
}
}
Query to get flat with building info 查询以获取建筑物信息
Flat::with('building')
->where('Building_Owned_By', '=',Auth::user()->Login_Id)
->orderBy('Flat_Name')
->get(array('Flat_Id as flatId', 'Flat_Name as flatName'))
->toArray();
Try this: 尝试这个:
Flat::with(array('building'=>function($query){
$query->where('Building_Owned_By', '=',Auth::user()->Login_Id)
}))->where('Fk_Building_Id', '=',$buildingid)->orderBy('Flat_Name')
->get(array('Flat_Id as flatId', 'Flat_Name as flatName'))->toArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.