简体   繁体   English

如何在Laravel 5中返回自定义查询结果

[英]How to return customized query result in Laravel 5

User Table 用户表

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

Car Table 车台

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

I'm using Query Builder and my query: 我正在使用查询生成器和查询:

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

it truncated created_at and updated_at from car table and it gets me: 它从汽车表中截断了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",
}

And I want to make our query result become, How can I do this? 我想使我们的查询结果变为,该怎么做? Any solutions? 有什么办法吗?

{
  "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"
  }
}

.

Try this and see what you get: 尝试一下,看看会得到什么:

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

1) Use Eloquent > 2) Define Relationships 1)使用口才> 2)定义关系

User.php 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');
    }

And for your query 并为您查询

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

Define the below code in your User Model & find it automatically fetched in your query, 在用户模型中定义以下代码,并在查询中自动找到该代码,

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

here is your query, 这是您的查询,

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

Also don't forget to define foreign key relationship 也不要忘记定义外键关系

  1. Make a relation ship in model. 在模型中建立关系。

     public function car() { return $this->hasOne('App\\Car'); } 
  2. Then use the with() 然后使用with()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM