user3351236
user3351236

Reputation: 2538

How Laravel generates SQL queries

I have created a one-to-many relationship. Here are the model classes.

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

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

Then I try to retrieve photos:

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

Here is a query log I got. I do not see the photo='ut.jpg'. So how laravel generate SQL?

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

Upvotes: 0

Views: 97

Answers (5)

benji127
benji127

Reputation: 345

You could: Run A Select Query

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

All this is well-documented in : --https://laravel.com/docs/5.0/database

Upvotes: 0

Matthias S
Matthias S

Reputation: 3563

You queried all photos by using this:

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

By using User::find(1)->photos you receive a Laravel Collection. Those collections have a where method as well. So basically, you are running SQL to get all photos of User 1 and then you just filter that collection to only show you the item with photo ut.jpg.

Instead, you can use brackets to get the relationship, and then query that. Your query then becomes

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

Instead of naming it $photos you should name it $photo, as you are querying with first - which will result only in one object (or null).

Upvotes: 1

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

Try this

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

must be use ->photos() instead of ->photos.

For see sql query use

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

Upvotes: 3

Mohammad hayajneh
Mohammad hayajneh

Reputation: 674

your query $photos = User::find(1)->photos->where('photo', 'ut.jpg')->first(); is incorrect, laravel didnt see the where condition if you do this

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

})->where('id',1)->first();

thats the correct query to get the user photo

Upvotes: 0

kapitan
kapitan

Reputation: 2232

Can you please try this:

$photo = 'ut.jpg';

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

Upvotes: 0

Related Questions