Skip to content
Advertisement

Left Join – In Eloquent

I would like to connect user table and like table based on the user_id

So I have this Model

user.php

public function like()
{
    return $this->belongsTo('AppModelsLike', 'users_id', 'id');
}

like.php

public function user()
{
    return $this->belongsTo('AppModelsUser', 'id', 'user_id');
}

and my query

$mentor = $this->article->with("articlecategory")->with(["user.like"])->orderby("id", "DESC")->get();

I would like to return the ‘likes’ table inside the ‘user’ but it doesnt work. I would like to left join it.

What am I doing wrong?

enter image description here

enter image description here

Advertisement

Answer

Well, you need to use one-to-many relation to get likes for the specified user. And to do that you need to use hasMany() method on the User model as the following:

<?php

public function likes()
{
    return $this->hasMany('AppModelsLike', 'user_id', 'id');
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement