【问题标题】:I want to combine two tables by selecting the id entered by the user in Laravel我想通过选择用户在 Laravel 中输入的 id 来组合两个表
【发布时间】:2020-03-20 07:45:17
【问题描述】:

我想检索 user_detail 表中的全名列,方法是用户首先使用查询生成器在 Order 表中输入选定的 id

在订单表中是这样的

 +"id": 1
  +"order_detail_id": 115
  +"user_id": 3
  +"status": "pending"
  +"updated_at": "2019-11-22 17:53:56"
  +"created_at": "2019-11-22 15:44:28"

在表 user_detail 中看起来像这样

 +"id": 3
  +"full_name": michael jackson
  +"address": "bla bla bla"
  +"updated_at": "2019-11-22 17:53:56"
  +"created_at": "2019-11-22 15:44:28"

我想如果用户输入 id 1 它会像这样输出

            "id": 1,
            "order_detail_id": 115,
            "user_id": 3,
            "full_name": "michael jackson",
            "address" : "bla bla bla" 
            "status": "pending"

我尝试使用此代码,但仍然出现错误

 $cekclient = DB::table('order')
                                ->where('id',$request->id)
                                ->join('user', 'user.id', '=', 'order.user_id')
                                ->select('order.*','user.name','user.address',)
                                ->get();

            dd($cekclient);

【问题讨论】:

    标签: sql database laravel laravel-5 join


    【解决方案1】:

    试试这个代码。请给表别名并在选择和加入中使用它们。

    $cekclient  = DB::table('order as or')
                ->select('or*','u.name','u.address') // here you can add column names which you need in output
                ->leftJoin('user as u', 'u.id', '=', 'or.user_id')
                ->where('or.id',$request->id) // here if you need data by id of user then use u.id in where insead of or.id
                ->get();
    

    【讨论】:

    • 查询生成器是否必须是模型中的关系?因为我收到这样的错误,即使在数据库中我已经关联了它?未定义的表:7 错误:关系
    • 查询生成器与 eloquent 不同。查询生成器不使用模型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    相关资源
    最近更新 更多