dousong9729 2015-01-20 17:44
浏览 13

Laravel 5离开了加入关系

I have two database tables: users and students. A student is a user, but has extra data (address). I have a belongsTo('User') relationship in my Student model.

If I now query the Student model like this:

$this->student
    ->with('user')
    ->first();

I get this result:

{
    "id": 1,
    "user_id": 12,
    "street": "Petershof",
    "house_number": "3787",
    "postal_code": "8161 NM",
    "city": "Tienhoven",
    "user": {
        "id": 12,
        "email": "bvierdag@yahoo.nl",
        "first_name": "Nathan",
        "last_name": "van Dijk",
        "name": "Nathan van Dijk"
    }
}

However, I want to flatten the result, so that the user fields are in the parent (Student) object. Like this:

{
    "id": 1,
    "user_id": 12,
    "street": "Petershof",
    "house_number": "3787",
    "postal_code": "8161 NM",
    "city": "Tienhoven",
    "email": "bvierdag@yahoo.nl",  // = user field
    "first_name": "Nathan",        // = user field
    "last_name": "van Dijk",       // = user field
    "name": "Nathan van Dijk"      // = user field
}

I have tried to use leftJoin('users', 'user_id', '=', 'users.id') instead of with(), but then I lose my virtual attribute 'name' (defined in the User model) and also can't query relations of User anymore.

How can I achieve this in a clean way?

  • 写回答

2条回答 默认 最新

  • doudi8829 2015-01-20 20:59
    关注
    $this->student
      ->leftJoin('users', 'users.id', '=', 'students.user_id')
      ->select(
        'students.*',
        'users.email',
        'users.first_name',
        'users.last_name',
        DB::raw("concat(users.first_name, ' ', users.last_name) as name"),
      )->first();
    

    You could drop the table in select like users.email in this case.

    The relations will work just the same, I suppose the problem was only with overriding students id with users id, if you didn't specify the select and just grabbed all the fields.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度