My query to search for a username in a store listing is as follows:
$data = Store::join('users AS b', 'b.id', '=', 'stores.user_id')
->where('b.name', 'like', '%hazard%')
->paginate();
It works. But I use join to do it.
How can I do it using belongto?
My store model is like this :
class Store extends Model
{
protected $fillable = ['name', 'user_id', ...];
public function user()
{
return $this->belongsTo(User::class,'user_id', 'id');
}
...
}
BelongsTo is a inverse of HasOne. We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone models. I'm giving hasOne relation from User to Phone. class User extends Model { /** * Get the phone record associated with the user.
with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.
This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.
Belongs To relation defines that an entity is owned by a related entity on the exclusive matter. Example: a post belongs to an author, a comment belongs a post. Most belongsTo relations can be created using the inverse option of the declared hasOne or hasMany relation.
Use whereHas()
:
Store::whereHas('user', function($q) use($username) {
$q->where('name', 'like', '%'.$username.'%');
})->paginate(5);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With