User Model :
public function favorites()
{
return $this->hasMany(Favorite::class);
}
Controller :
//return auth()->user()->favorites()->get();
//return auth()->user()->favorites;
can someone explain the difference betwen the two codes ? and when i should use each one?
CodePudding user response:
Let me explain it practically:
If the above query looks like this
// return auth()->user()->favorites()->where('active', true)->get();
// return auth()->user()->favorites->where('active', true);
then its SQL query be like this
// SQL of first query
select * from `favorites` where `favorites`.`user_id` = 1 and `favorites`.`user_id` is not null and `active` = 1
// SQL of second query
select * from `favorites` where `favorites`.`user_id` = 1 and `favorites`.`user_id` is not null
Did you see differences in two SQL?
Now, Let me explain it in words:
If you add some condition after favorites()
like above, it will fetch all filtered result from database. But if you add some condition after favorites
it will filter the result which is already fetched from the database.
Although, I'm not good at explanations, I hope you understand clearly between the two codes.