【问题标题】:How Laravel generates SQL queriesLaravel 如何生成 SQL 查询
【发布时间】:2019-08-29 09:07:13
【问题描述】:

我创建了一对多的关系。这是模型类。

class Photo extends Model
{
    public function user(){
        return $this->belongsTo('App\User');
    }
}

class User extends Authenticatable
{ 
    public function photos(){
        return $this->hasMany('App\Photo');
    }
}

然后我尝试检索照片:

$photos = User::find(1)->photos->where('photo', 'ut.jpg')->first();

这是我得到的查询日志。我没有看到照片='ut.jpg'。那么 laravel 是如何生成 SQL 的呢?

select * from `photos` where `photos`.`user_id` = 1 and `photos`.`user_id` is not null

【问题讨论】:

标签: php laravel laravel-5.8


【解决方案1】:

你能试试这个吗:

$photo = 'ut.jpg';

$photos = User::find(1)->whereHas('photos', function ($query) use($photo){
return $query->where('photo', $photo);
})->first();

【讨论】:

    【解决方案2】:

    您的查询 $photos = User::find(1)->photos->where('photo', 'ut.jpg')->first(); 不正确,如果您这样做,laravel 没有看到 where 条件

    User::whereHas('photos', function($q) {
          $q->where('photo', 'ut.jpg');
    
    })->where('id',1)->first();
    

    这是获取用户照片的正确查询

    【讨论】:

    • 我以文档laravel.com/docs/5.8/eloquent-relationships#one-to-many 中的示例为例。 $comment = App\Post::find(1)->cmets()->where('title', 'foo')->first();我得到的结果是正确的。但查询不是。
    • @user3351236 $comment = App\Post::find(1)->cmets()->where('title', 'foo')->first(); where 条件是在帖子上而不是评论上,而你所做的是在照片上而不是用户上
    【解决方案3】:

    你可以: 运行选择查询

    $photos = DB::select('select * from photos where id = ?', [1]);
    

    所有这些都在以下文件中有详细记录: --https://laravel.com/docs/5.0/database

    【讨论】:

      【解决方案4】:

      试试这个

      $photos = User::find(1)->photos()->where('photo', 'ut.jpg')->first();
      

      必须使用->photos() 而不是->photos

      查看sql查询使用

      $sql = User::find(1)->photos()->where('photo', 'ut.jpg')->toSql();
      

      【讨论】:

        【解决方案5】:

        你用这个查询了所有照片:

        $photos = User::find(1)->photos->where('photo', 'ut.jpg')->first();
        

        通过使用User::find(1)->photos,您会收到Laravel Collection。这些集合也有一个where 方法。所以基本上,您正在运行 SQL 来获取 User 1 的所有照片,然后您只需过滤该集合以仅向您显示带有照片 ut.jpg 的项目。

        相反,您可以使用括号来获取关系,然后进行查询。 然后您的查询变为

        $photos = User::find(1)->photos()->where('photo', 'ut.jpg')->first();
        

        不应将其命名为 $photos,而应将其命名为 $photo,因为您使用 first 进行查询 - 这只会产生一个对象(或 null)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-06-01
          • 2019-09-08
          • 1970-01-01
          • 2021-04-30
          • 2023-01-14
          • 2021-08-07
          • 2017-09-28
          • 2017-04-22
          相关资源
          最近更新 更多