1

我有3张桌子,

  1. 国家:身份证,姓名

  2. 省份:id、name、country_id

  3. 城市:id、name、province_id

我在模型中定义了如下关系,

国家型号:

    public function Provinces()
        {
            return $this->hasMany('App\Province');
        }

省份型号:

        public function Country()
        {
            return $this->belongsTo('App\Country');
        }

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

城市模型:

    public function Province()
        {
            return $this->belongsTo('App\Province');
        }

我正在使用下面的查询,但它用国家名称覆盖了所有数据。

    $city = DB::table('cities')
        ->join('provinces', 'cities.province_id', '=', 'provinces.id')
        ->join('countries', 'provinces.country_id', '=', 'countries.id')
        ->select('cities.name','provinces.name','countries.name')
        ->get();

我想从 laravel 5 中的这些表中仅获取城市名称、省份名称、国家名称的结果。你能帮我吗?

4

4 回答 4

3

尝试使用as

->select('cities.name as city_name', 'provinces.name as province_name', 'countries.name as country_name')
于 2016-06-18T20:24:57.483 回答
0

你会试试这个:

$city = DB::table('cities')
    ->join('provinces', 'cities.province_id', '=', 'provinces.id')
    ->join('countries', 'provinces.country_id', '=', 'countries.id')
    ->get(['cities.name', 'provinces.name', 'countries.name']);

我希望它对你有帮助!

于 2016-06-18T20:36:00.500 回答
0

好的,这将是一个具体的答案,了解 laravel 中的 realtions 并查看这些

class example1 extends Model
    {
      public function examplefunction() {
        return $this->hasMany('App\othermodel', 'id');
    }
}

然后使用这个查询

$abc=example1::with('examplefunction')->get();

然后你就可以通过使用这个来看看 laravel 关系你可以获得组合结果

于 2017-11-20T13:51:49.177 回答
-1
 $products = User::select('id', 'email', 'first_name', 'last_name','country_code','mobile')->get()->toArray();
       $gaurang = Ticket_Thread::select('body','title','resolv_note')
于 2019-01-31T06:28:17.243 回答