Skip to content

Search by related model (belongsTo relation) #342

@EhsanZ

Description

@EhsanZ

Hi
Assume that I have two models: User & Article.
I want to get all articles which have been written by high school students.
It seems so easy but I'm giving up with it, I tried those two solutions:

$articles = Article::with(
array('user'=>function($user_query)
{
$user_query->where('school_level','=','high school');
})
)->get();

And:

$articles = Articles::where('user.school_level','=','high school');

Both don't work, SQL developers use join to solve this problem, what should we use?
Also, if the relationship was Has Many the search works good using whereHas, for example :

$users = User::whereHas(
'articles', function($article_query)
{
$article->where('subject','like','some text');
})->get()

Any suggestions?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions