@jesse_orange_newable did you get the query by debugging or this is what you expect?
You can check where do you go wrong like this:
dd(Team::first()->articles()->toSql());
And make sure that the SQL is the one that you expect.
Hi everyone, I'm trying to understand a relation I haven't paid much attention to, until recently.
In my setup I have 3 models: Team, User and Article with relations between User and Article, andTeam and User
/**
* A user belongs to a team
*
* @return void
*/
public function team()
{
return $this->belongsTo(Team::class, 'department', 'name');
}
/**
* Get all of the articles associated with this user
*/
public function articles()
{
return $this->hasMany(Article::class, 'user_username', 'username');
}
I've also added the inverse of the given relations, so at the moment I can do
$team->users
$user->team
$article->author
$user->articles
I've been trying to get the articles written per department so this was my thought process:
I feel like this is a perfect place to use a hasManyThrough so I tried this in the Team model:
/**
* Get all of the articles for this department by going through users who authored articles
* hasManyThrough: [farthest model]|[intermediate model]
*/
public function articles()
{
return $this->hasManyThrough(
'App\Article',
'App\User',
'department', // Foreign key on users table...
'user_username', // Foreign key on articles table...
'id', // Local key on teams table...
'username' // Local key on users table...
);
}
However, this returns null.
Essentially this query:
SELECT * FROM articles
LEFT JOIN users ON articles.user_username = users.username
WHERE user_username IS NOT NULL
AND users.department = 'Digital'
Or something similar to this?
"select * fromarticleswhere exists (select * fromuserswherearticles.user_username=users.usernameanddepartment= ?)"
Please or to participate in this conversation.