我有一个名为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();
但它什么也没有回报。
我们如何在Eloquent Orm中执行内连接(我不想使用流畅的查询)?
更新
感谢@Creator的宝贵时间和帮助。他帮助我找到了这个。解决方案是我们必须使用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();
答案 0 :(得分:4)
这样做:
class Building extends Eloquent {
protected $primaryKey = "Building_Id";
protected $table = 'buildings';
.......
.......
public function flat()
{
return $this->HasMany('Flat', 'Fk_Building_Id', 'Building_Id');
}
}
查询以建造所有单位:
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();
答案 1 :(得分:1)
试试这个:
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();