Laravel从两个表中联接,包括空

时间:2020-01-31 06:16:00

标签: mysql laravel laravel-5 eloquent mysql-workbench

我有3张桌子listings, cities, state

listings表:

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可为空!

cities表:

id | state_id | name | ...|

City型号:

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');

states表:

id | name ...|

型号:

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_idcity_id的外键。两者之间的关系是一个城市或州与许多商家信息。

city表也具有外键state_id,并将一个州与许多城市相关联。

我想从statescities中选择所有内容,并对每个城市/州的列表中的行进行计数,在这里我可以:

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();

问题是我希望一个集合中的所有城市和州都有另一个键/属性-计算该城市/州的列表。

是城市还是州,都没关系,我只想要他们的名字和计数列表。

我正在使用MySQL的最新Laravel版本。

1 个答案:

答案 0 :(得分:1)

不确定它是否完全满足您的需求,但是如果您想避免任何复杂的SQL查询和联合,则可以执行以下操作:

$states = State::with(['listings', 'listings_count'])->get();
$cities = City::with(['listings', 'listings_count'])->get();

$locations = $states->merge($cities);

如果您的收藏夹很大,那么在性能上并不是很好,但是对于较小的收藏夹仍然有用。