【问题标题】:Eloquent select with() based on foreign key基于外键的 Eloquent select with()
【发布时间】:2017-05-04 11:39:40
【问题描述】:

我有一个包含用户数据的表格 (users) 和一个包含价格的表格 (prices)。 我的价格表可以包含多个价格公关。用户,因为我想保留历史数据。

我已将我的关系定义为一对一

$this->hasOne("App\Model\Price","userid","id")->orderBy("id","desc")->take(1);

让我看到用户当前的价格。

我现在要做的是选择当前价格为 100 的每个用户,但我该怎么做呢?我知道我可以选择左连接,但是当我阅读文档,应该可以不用左连接。

我构建了一个伪查询来解释我所追求的; User::with("price")->where("prices.price","100")->get();

我已通读文档 (Eloquent: Querying relationships),但这似乎对我的问题没有用处。

我也在这里阅读了几个关于 SO 的问题,但不幸的是无济于事。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    你可以试试这个:

    $currentPrice = 100;
    $users = User::whereHas('price', function($query) use ($currentPrice) {
        $query->where('price', $currentPrice); // price is the field name
    })
    ->with("price")->get();
    

    由于每个用户的价格不止一个,因此您还可以声明另一种关系方法来获取所有价格模型而不是一个,您可以使用以下方法来实现:

    // In User model
    public function prices()
    {
        return $this->hasMany("App\Model\Price", "userid", "id");
    }
    

    在这种情况下,with::price 将为您提供最后一条记录,with::prices 将为您提供所有相关价格。因此,如果您愿意,您可以编写类似以下内容的内容,以获取所有相关价格且(最新/当前)价格为 100 的所有用户:

    $currentPrice = 100;
    $users = User::whereHas('price', function($query) use($currentPrice) {
        $query->where('price', $currentPrice); // price is the field name
    })
    ->with("prices") // with all prices
    ->get();
    

    【讨论】:

      【解决方案2】:

      您可以使用whereHas()with() 的组合作为:

      $users = User::whereHas("price", function($q) use ($currentPrice) {
                     $q->where("price", $currentPrice);
                  })
                  ->with(["price" => function ($q) {
                      $query->where("price", $currentPrice);
                  })
                  ->get();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-10
        • 2018-06-04
        • 2012-03-29
        • 1970-01-01
        • 2016-08-26
        • 2020-02-16
        相关资源
        最近更新 更多