Sql Laravel雄辩地连接表和计数相关
考虑到下表结构,我如何使用join和雄辩: 我有一张桌子Sql Laravel雄辩地连接表和计数相关,sql,join,laravel-4,eloquent,Sql,Join,Laravel 4,Eloquent,考虑到下表结构,我如何使用join和雄辩: 我有一张桌子 --------------------- ID | Name --------------------- 1 | Property Name 我没有房间 ---------------------- RoomID | Property ---------------------- A-212 | 1 ---------------------- F-1231 | 1 这里的属性是外键 然后我想得到所有的财产,并计
---------------------
ID | Name
---------------------
1 | Property Name
我没有房间
----------------------
RoomID | Property
----------------------
A-212 | 1
----------------------
F-1231 | 1
这里的属性是外键
然后我想得到所有的财产,并计算他们每个人有多少个房间
检索所有内容的查询如下所示
class PropertiesRepository extends EloquentBaseRepository implements PropertiesInterface
{
use TaggableRepository;
/**
* Construct
* @param Properties $properties
*/
public function __construct( Properties $properties )
{
$this->model = $properties;
}
/**
* Get all properties joining rooms
* @return Properties
*/
public function getAll()
{
return $this->model->get();
}
}
如何扩展此查询以获得所需的结果?这更像是MySQL的join+group+select技巧,包括以下步骤
roomscont=0
的行,请使用Join
,否则请使用leftJoin
)groupBy
by primaryKey避免重复连接count
在属性模型类上定义关系:
<?php
namespace App\Models;
class Property extends Model {
public function rooms() {
return $this->hasMany(Room::class);
}
}
这将给结果增加一个房间数。只有代码的答案在堆栈溢出上价值很低,因为它们在教育/授权OP和未来的研究人员方面做得很差。堆栈溢出不仅仅是一个代码段转储地。请解释您的答案。可以使用此选项,但请注意,这将在内部运行两个查询。多对多关系如何?您必须定义一个belongToMany关系,而不是hasMany。其他一切都是一样的。请参见此处,了解如何定义多对多关系:
<?php
namespace App\Models;
class Property extends Model {
public function rooms() {
return $this->hasMany(Room::class);
}
}
$properties = Property::withCount(['rooms'])->get();