Laravel 如何生成 SQL 查询

How Laravel generates SQL queries

我已经创建了一对多关系。这是模型 类.

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

你能试试这个吗:

$photo = 'ut.jpg';

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

您的查询 $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();

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

你可以: 运行一个Select查询

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

所有这些都在 : --https://laravel.com/docs/5.0/database

试试这个

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

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

查看sql查询使用

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

您使用此查询了所有照片:

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

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

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

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

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