基于外表属性

时间:2015-09-02 18:59:27

标签: laravel laravel-5 eloquent foreign-collection

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

  • 场地
  • 城市

    这是关系:
    city有多个locationslocation属于city
    location属于venuevenue只有一个location

我在位置表上有一个city_id属性,您可以从关系中找到它
问题很简单:
我怎样才能获得属于特定城市的场地? 我期望的雄辩查询看起来像这样:
$venues=Venue::with('location')->where('location.city_id',$city->getKey());

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

2 个答案:

答案 0 :(得分:5)

有两种选择:

$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();

答案 1 :(得分:1)

重要的是要记住,每个雄辩的查询都会返回一个集合,因此您可以对结果使用“collection methods”。正如在其他答案中所说,你需要一个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'));