用户表
+------------+
| 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();
它从car table中截断了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();
答案 1 :(得分:0)
1)使用Eloquent> 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);
答案 2 :(得分: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();
另外不要忘记定义外键关系
答案 3 :(得分:0)
在模型中建立关系。
public function car()
{
return $this->hasOne('App\Car');
}
然后使用with()
user::where('uid', '=', $uid)->with('car')->get();