jeudi 30 janvier 2020

Laravel join from two tables including null

I have 3 tables listings, cities, state.

listings table:

id | city_id | state_id |...|

Listing model:

class Listing extends Model{

function city(){
    return $this->belongsTo('App\Models\City');
}

function state(){
    return $this->belongsTo('App\Models\State');
}

Listing migration:

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 is nullable !

cities table:

id | state_id | name | ...|

City Model:

class City extends Model{

    public function listings(){
        return $this->hasMany('App\Models\Listing');
    }

    function state(){
        return $this->belongsTo('App\Models\State');
    }

Migration:

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 table:

id | name ...|

Model:

class State extends Model{

    public function listings(){
        return $this->hasMany('App\Models\Listing');
    }

    function cities(){
        return $this->hasMany('App\Models\City');
    }

Migration:

public function up(){
    Schema::create('states', function (Blueprint $table) {
        $table->integer('id')->unsigned()->index()->unique()->autoIncrement();
        $table->string('name');

listings table has foreign keys to state_id and city_id. The relation for both is one city or state to many listings.

city table has foreign key state_id, too and relation one state to many cities.

I want to select everything from states and cities and count rows from listings table for each city/state, where I can:

foreach($listings as $listing){
    
}

I am using the latest Laravel version with MySQL.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire