【问题标题】:Query builder in Laravel in not workingLaravel 中的查询生成器无法正常工作
【发布时间】:2018-08-18 09:32:23
【问题描述】:

我有在 MySQL 中运行良好的 sql 查询。我想使用连接用户表从配置文件表中获取配置文件 ID。

SELECT profiles.profile_id FROM profiles 
   left JOIN users on profiles.id = users.id where users.id = 1

Laravel Query builder 查询是

    $my_user_id = Auth::user()->id;
    $my_id =   DB::table('profiles')->select('profiles.profile_id')
                   ->leftjoin('users','users.id' ,'=' ,'profiles.id')
                   ->pluck('profiles.profile_id')
                   ->where('users.id',$my_user_id)
                   ->first();

【问题讨论】:

  • 是否需要使用joins?我认为您可以定义一种关系(仅在 Laravel 中,而不一定在您的数据库中)来提取数据

标签: laravel laravel-query-builder


【解决方案1】:

pluck() 之前调用where()select() 不是必需的):

 $my_id = DB::table('profiles')
    ->leftJoin('users', 'users.id', '=' , 'profiles.id')
    ->where('users.id', $my_user_id)
    ->pluck('profiles.profile_id')
    ->first();

你也可以用value()缩短它:

$my_id = DB::table('profiles')
    ->leftJoin('users', 'users.id', '=' , 'profiles.id')
    ->where('users.id', $my_user_id)
    ->value('profiles.profile_id');

【讨论】:

    【解决方案2】:

    您还应该选择 id 来执行连接:

    DB::table('profiles')->select('profiles.profile_id', 'profiles.id')
                         ->leftjoin('users','users.id' ,'=' ,'profiles.id')
                         ->where('users.id',$my_user_id)
                         ->pluck('profiles.profile_id')
                         ->first();
    

    【讨论】:

    • 这个查询仍然没有返回任何内容。 SQL 查询运行良好,但这个 laravel 查询不工作。
    • 使用关系怎么样?
    • where 子句将先出现然后采摘,现在它已解决。
    • 但是你也必须选择id不是吗?
    猜你喜欢
    • 2015-01-12
    • 1970-01-01
    • 2020-03-16
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2015-12-16
    • 1970-01-01
    相关资源
    最近更新 更多