2017-04-17 15 views
1

用戶表如何Laravel返回定製查詢結果5

+------------+ 
| User | 
+------------+ 
| uid  | 
| name  | 
| created_at | 
| updated_at | 
+------------+ 

車表

+------------+ 
| Car  | 
+------------+ 
| cid  | 
| uid  | 
| car_name | 
| created_at | 
| updated_at | 
+------------+ 

我使用查詢生成器和我的查詢:

DB::table('user') 
    ->join('car', 'user.uid', '=', 'car.uid') 
    ->where('user.uid', '=', $uid) 
    ->get(); 

它截斷created_at和updated_at從車表,它得到我:

{ 
    "uid": 5, 
    "name": "Alexander Lowe DVM", 
    "created_at": "2017-04-01 18:12:45", 
    "updated_at": "2017-04-01 18:12:45", 
    "cid": 5, 
    "car_name": "BMW X8", 
} 

而我想讓我們的查詢結果成爲,我該怎麼做?任何解決方案

{ 
    "uid": 5, 
    "name": "Alexander Lowe DVM", 
    "created_at": "2017-04-01 18:12:45", 
    "updated_at": "2017-04-01 18:12:45", 
    "car": { 
    "cid": 5, 
    "car_name": "BMW X8", 
    "created_at": "2017-04-01 18:12:45", 
    "updated_at": "2017-04-01 18:12:45" 
    } 
} 

+0

您可以使用雄辯模型並定義它們之間的關係並獲得結果。 –

回答

0

試試這個,看看你會得到什麼:

$users = DB::table('user') 
      ->join('car', 'user.uid', '=', 'car.uid') 
      ->where('user.uid', '=', $uid) 
      ->select('user.*', 'car.created_at', 'car.updated_at') 
      ->get(); 
0

1)使用雄辯> 2)定義關係

user.php的

// for one to many relationship 
    public function car() { 
     return $this->hasMany(Car::class, 'uid'); 

//OR for one to one relationship 
     return $this->hasOne(Car::class, 'uid'); 
    } 

併爲您的查詢

User::with('car')->find($uid); 
+0

我可以做到這一點,而不使用雄辯嗎? – RaxPat

0

定義下面的代碼您的用戶模型&發現它在您的查詢自動獲取,

public function car() 
{ 
    return $this->hasOne('App\Car'); 
    //return $this->hasMany('App\Car'); //Use this if user has multiple cars 
} 

這裏是你的查詢,

DB::table('user') 
    ->where('user.uid', '=', $uid) 
    ->with('car') 
    ->get(); 

也不要忘記定義外鍵關係

+0

我可以在不使用口頭表達的情況下做到這一點嗎? – RaxPat

0
  1. 作出的關係在模型中發貨。 公共功能車() {return $ this-> hasOne('App \ Car'); }
  2. 比使用with() user :: where('uid','=',$ uid) - > with('car') - > get();