Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 1 year ago.
0

http://laravel.com/docs/5.1/eloquent-relationships#querying-re...

Eloquent can be tricky. You write queries one way which you think makes sense but you then realize there are many ways that make sense. For the way you have it defined, I think this is your approach

$name = "category name";

$cities = App\City::whereHas('rest', function ($query) use($name) {
    $query->category()->where('name', $name);
})->get();

edit: this might work?

$cities = App\City::all();
$category = $cities->rest()->category()->where('name', $name);

I would also suggest running dd($query->toSql()) for further learning on relationships :]

Last updated 8 years ago.
0

Thank you I really appreciate it but it didn't work for me. But it gave me an idea and I found another way.

    $category = App\Category::find(1);
    $rests = $category->rest()->where('city_id', '=', '1')->get();

    foreach($rests as $rest){
        echo $rest->name, "<br>";
    };

What do you think about it?

0

Hey, i thought about another way with HasManyThrough but it didn't work for me for some reasons. so here what i did to solve the problem:

Route::get('food/{city}/{name}', function($city, $name){
    $category = App\Category::where('name', '=', $name)->first();
    $city = App\City::where('name', '=', $city)->first();

    $rests = $category->rest()->where('city_id', '=', $city->id)->get();

    foreach($rests as $rest){
        echo $rest->name, '<br>';
    }
});
0

Sign in to participate in this thread!

Eventy

Your banner here too?

itay012 itay012 Joined 19 Sep 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.