我有3个表格列表,城市,州
。
列表
表:
id city_id state_id...
列表模型:
class Listing extends Model{
function city(){
return $this->belongsTo('App\Models\City');
}
function state(){
return $this->belongsTo('App\Models\State');
}
列表迁移:
public function up(){
Schema::create('listings', function (Blueprint $table) {
$table->integer('id')->unsigned()->index()->unique()->autoIncrement();
$table->integer('city_id')->nullable();
$table->integer('state_id')->nullable();
....
city_id/state_id
可为空!
城市
表:
ID state_id名称...
城市
模型:
class City extends Model{
public function listings(){
return $this->hasMany('App\Models\Listing');
}
function state(){
return $this->belongsTo('App\Models\State');
}
迁移:
public function up(){
Schema::create('cities', function (Blueprint $table) {
$table->integer('id')->unsigned()->index()->unique()->autoIncrement();
$table->integer('state_id')->nullable();
$table->string('name');
状态
表:
ID名称...
型号:
class State extends Model{
public function listings(){
return $this->hasMany('App\Models\Listing');
}
function cities(){
return $this->hasMany('App\Models\City');
}
迁移:
public function up(){
Schema::create('states', function (Blueprint $table) {
$table->integer('id')->unsigned()->index()->unique()->autoIncrement();
$table->string('name');
listings
表具有指向state_id
和city_id
的外键。两者的关系是一个城市或州与多个列表。
city
表也有外键state_id
并将一个州与多个城市联系起来。
我想从states
和cities
中选择所有内容,并从listings表中计算每个城市/州的行数,我可以:
foreach($listings as $listing){
{{$listing->city or state . ' | ' . $listing->all (count listings for current city/state)}}
}
我所尝试的是:
$locations = DB::table('listings')
->join('states', 'states.id', '=', 'listings.state_id')
->join('cities', 'cities.id', '=', 'listings.city_id')
->groupBy(['listings.city_id', 'listings.state_id' ])
->select(
'states.name.name as state',
'cities.name as city',
'states.id as state_id',
'city.id as city_id',
DB::raw("COUNT(listings.id) as countListings")
)->get();
问题是,我希望所有城市和州都在一个集合中,并为该城市/州提供另一个键/属性计数列表。
是城市还是州,没关系,我只想要他们的名字与计数列表。
我正在使用最新的Laravel版本与MySQL。
不确定它是否完全符合您的需要,但如果希望避免任何复杂的SQL查询和联合,可以执行以下操作:
$states = State::with(['listings', 'listings_count'])->get();
$cities = City::with(['listings', 'listings_count'])->get();
$locations = $states->merge($cities);
如果您的集合很大,就性能而言就不是那么好,但对于较小的集合仍然有用。