You can't do an inner join with relationships. Instead you should just do a regular join in Eloquent. You can find examples here: https://laravel.com/docs/5.8/queries#joins
Let me know if that works for you ;)
Hi guys
I'm currently practicing my Laravel skills by building a Twitter clone and i'm still relatively new at building eloquent queries.
I'm stuck building the "feed", which should consists of the statuses of the other user profiles the given user is following.
This is what my models looks like:
User.php
public function statuses()
{
return $this->hasMany(Status::class)->latest('updated_at');
}
public function following()
{
return $this->belongsToMany(User::class, 'follows', 'follower_user_id', 'followed_user_id');
}
public function followers()
{
return $this->belongsToMany(User::class, 'follows', 'followed_user_id', 'follower_user_id');
}
Status.php
public function user()
{
return $this->belongsTo(User::class);
}
This is what the MySQL query looks like:
SELECT statuses.*
FROM follows
INNER JOIN statuses ON follows.followed_user_id = statuses.user_id
WHERE follower_user_id = 151
ORDER BY statuses.created_at DESC
LIMIT 15;
Where 151 is the current user id and the limit is a pseudo pagination.
My current attempt at eloquent looks like this
auth()->user()->following()->with('statuses')->orderBy('created_at', 'desc')->paginate(15);
It is querying the correct followings along with ALL of their statuses, and its ordering by user.created_at and not status.created_at.
What have i missed?
@mstrauss This way you only get the statuses of everyone that you're following. You won't have your own statuses. And if you grab your own statuses separately you will most of the time have more than 15 results, so the pagination won't make any sense anymore.
Please or to participate in this conversation.