如何在Laravel中的雄辩ORM中编写内部联接? [英] How to write a inner join in Eloquent ORM in laravel?
本文介绍了如何在Laravel中的雄辩ORM中编写内部联接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为buildings
和flats
建筑物表格
Building_Id | Building_Name | .......| Building_Owned_By | ....
展平表
Flat_Id | Flat_Name | ........| Fk_Building_Id | .....
和在我的模型中
建筑物
class Building extends Eloquent {
protected $primaryKey = "Building_Id";
protected $table = 'buildings';
.......
.......
public function flat()
{
return $this->hasMany('Flat', 'Fk_Building_Id', 'Building_Id');
}
}
单位
class Flat extends Eloquent {
protected $primaryKey = "Flat_Id";
protected $table = 'flats';
.......
.......
public function building() {
return $this->belongsTo('Building','Fk_Building_Id', 'Building_Id');
}
}
以及在我的控制器中
$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();
但是它什么也没返回.
我们如何在雄辩的Orm中执行内部联接(我不想使用流利的查询)?
How can we perform inner joins in Eloquent Orm (I dont want to use fluent query)?
更新
感谢@Creator的宝贵时间和帮助.他为我找到了很多帮助.解决方案是我们必须使用其中有,然后将代码重写为
Thanks for @Creator for his valuable time and help. He helps me a lot for finding this. The solution is we have to use whereHas and we rewrite the code as
$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();
推荐答案
执行此操作:
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');
}
}
查询以获取建筑物信息
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();
这篇关于如何在Laravel中的雄辩ORM中编写内部联接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文