如何在laravel

时间:2018-10-30 09:12:19

标签: laravel

我有4个这样的模型

商家模型

class Merchant extends Model {
    public function city() {
       return $this->belongsTo('App\Model\Loc\City');
    }
}

城市模型

class City extends Model {
    public function province() {
       return $this->belongsTo('App\Model\Loc\Province');
    }
    public function merchant() {
       return $this->hasMany('App\Model\Merchant');
    }
}

省级模型

class Province extends Model {
    public function country() {
       return $this->belongsTo('App\Model\Loc\Country');
    }
    public function city() {
       return $this->hasMany('App\Model\Loc\City');
    }
}

国家模型

class Merchant extends Model {
    public function province() {
       return $this->hasMany('App\Model\Loc\Province');
    }
}

我想按国家ID显示商家,该怎么办? 我有这样的简单查询,如何实现到laravel查询生成器中

SELECT mer.* FROM
merchants AS mer,
city AS city,
province AS prov,
country AS country WHERE
mer.id_city = city.id_city
AND city.id_prov = prov.id_prov 
AND prov.id_country = country.id_country
AND country.id_country = 1

谢谢

2 个答案:

答案 0 :(得分:0)

您可以尝试此操作,也可以根据需要对其进行修改,希望它可以为您提供一条路径:

DB::table('merchants as mer')
    ->select(['mer.*', 'city.*', 'prov.*', 'country.*'])
    ->join('city', 'city.id_city', '=', 'mer.id_city')
    ->join('province as prov', 'prov.id_prov', '=', 'city.id_prov')
    ->join('country as c', 'c.id_country', '=', 'prov.id_country')
    ->where('c.id', 1)
    ->get();

答案 1 :(得分:0)

这个很好看。我在这里假设该国家拥有id = 1

$merchants = Merchant::whereHas('city', function ($city) {
    $city->whereHas('province', function ($province) {
        $province->where('id_country', '=', 1);
    });
})->get();