8

我正在使用 laravel 和雄辩的。
实际上,我在根据另一个表属性的条件过滤表中的结果时遇到问题。
我有 3 张桌子:

  • 场地
  • 城市


    这是关系:
    acity有很多locations, alocation属于 a city
    alocation属于 avenue并且 avenue有一个location

city_id在位置表上有一个属性,您可以从关系中找出它。

问题很简单:
我怎样才能获得属于特定城市的那些场地?
我期望的雄辩的查询看起来像这样:
$venues=Venue::with('location')->where('location.city_id',$city->getKey());

当然那是行不通的,但似乎这是一项常见的任务,并且会有一个雄辩的命令。
谢谢!

4

2 回答 2

10

几个选项:

$venues = Venue::whereIn('location_id', Location::whereCityId($city->id)->get->lists('id'))
    ->get();

或者可能使用whereHas

$venues = Venue::whereHas('location', function($query) use ($city) {
    $query->whereCityId($city->id);
})->get();
于 2015-09-02T19:10:26.847 回答
1

重要的是要记住每个 eloquent 查询都返回一个集合,因此您可以在结果上使用“集合方法”。因此,正如在其他答案中所说,您需要一个Eager Loading ,您需要根据您的关系从另一个表中请求要排序的属性,然后根据结果(即集合),您可以使用“sortBy”或“sortByDesc” “ 方法。

你可以看看下面的例子:

class Post extends Model {
        // imagine timpestamp table: id, publish, delete,
        // timestampable_id, timestampble_type
    public function timestamp()
    {
        return $this->morphOne(Timestamp::class, 'timestampable');
    }
}

然后在东西的视图方面:

$posts = App\Post::with('timestamp')->get(); // we make Eager Loading
$posts = $posts->sortByDesc('timestamp.publish');
return view('blog.index', compact('posts'));
于 2017-02-21T17:52:22.317 回答