【问题标题】:eloquent filter result based on foreign table attribute基于外部表属性的 eloquent 过滤结果
【发布时间】:2015-09-02 18:59:27
【问题描述】:

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

  • 会场
  • 城市


    以下是关系:
    一个city 有很多locations,一个location 属于一个city
    一个location 属于一个venue,一个venue 有一个location

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

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

这当然行不通,但似乎这是一项常见任务,并且会有一个 eloquent 命令用于它。
谢谢!

【问题讨论】:

  • 你试过HasManythrough吗?一个城市通过位置有许多场所。通过相关的 eloquent 模型访问远距离关系?
  • @mdamia 这个扭结关系是belongsToManyThrough,它还没有在laravel eloquent中实现

标签: laravel laravel-5 eloquent foreign-collection


【解决方案1】:

几个选项:

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

【讨论】:

  • 上帝保佑你!第二个就像一个魅力。但我的问题有两个部分,我在这里没有提到第二部分。我有一个标签模型,它与场地有多对多的关系。给定一串标签名称,如何过滤呢?我应该为它创建另一个问题吗?
  • 刚刚弄清楚 whereHas 期望将关系作为第一个参数,所以这也很有效->whereHas('tags', function ($query) use ($tag) { $query->whereName($tag); })
  • 这个查询的大概性能怎么样,这样查询多次效率高吗?
  • 如果你的索引是好的应该是非常好的。我刚刚运行的测试查询生成的 SQL 是:select * from companies where (select count(*) from locations where locations.company_id = companies.id and id = ?) >= 1,所以它实际上创建了一个子查询。
【解决方案2】:

请务必记住,每个 eloquent 查询都会返回一个集合,因此您可以在结果上使用“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'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多