【问题标题】:Laravel 5: Eloquent whereHas subquery doesn't filter resultsLaravel 5:雄辩 whereHas 子查询不过滤结果
【发布时间】:2017-03-10 13:34:03
【问题描述】:

我正在尝试使用关系从模型中检索一些结果,并且我正在尝试对该关系应用一些过滤器。

这是模型:

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class UserProduct extends Model
{

    protected $primaryKey = null;
    public $incrementing = false;
    protected $table = "user_product";

    public $fillable = [
        ...
        "product_id",
        "user_id",
        "is_featured",
        "is_hidden_from_latest"
        ...
    ];

    public function product()
    {
        return $this->belongsTo("\\App\\Models\\Product", "product_id", "id");
    }

    ...

}

这里是相关的模型:

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = "products";

    public $timestamps = false;

    public $fillable = [
        ...
    ];

    public function userProduct()
    {
        return $this->hasOne("\\App\\Models\\UserProduct", "product_id", "id");
    }

    ...

}

这里是UserProduct型号与产品关系的查询:

$user_products = UserProduct::with("product")
    ->whereHas("product", function($q) {
        $q->where("product_status", "live")
            ->where("parent_child", "Child");
    })->where("is_featured", 1)
        ->orWhere("is_hidden_from_latest", 0)
        ->orderBy("is_featured", "desc")
        ->orderBy("updated_at")
        ->get();

问题是whereHas 子查询似乎没有过滤任何东西,无论我使用什么值来比较每个product_statusparent_child

有什么我做的不对吗?


更新:似乎游戏破坏者是最后这两个where() 语句:

....
->where("is_featured", 1)
->orWhere("is_hidden_from_latest", 0)
....

更具体地说是orWhere() 声明。

【问题讨论】:

  • 只是出于好奇。为什么你们的关系会出现双重反弹?
  • 使用字符串定义命名空间时,string escaping rules可能适用,为避免这种情况,建议使用双反斜杠。
  • 反斜杠用于访问命名空间,我不明白为什么要加倍。
  • 因为在 php 中包含命名空间,就像在许多其他支持命名空间的语言中一样,不需要引号,但在这种情况下,我使用字符串来定义相关模型,因为在某些情况下反斜杠可能是逃脱使用反斜杠更安全。不过,这不是必需的。
  • 你已经解决了这个问题吗?

标签: php mysql laravel eloquent


【解决方案1】:

试试这个方法

$user_products = UserProduct::with("product")
->whereHas("product", function($q) {
    $q->where("product_status", "live")
    ->where("parent_child", "Child");
})
->where(function ($query) {
    $query->where("is_featured", 1)
    ->orWhere("is_hidden_from_latest", 0);
})
->orderBy("is_featured")
->orderBy("updated_at")
->get();

【讨论】:

  • 等等,你在过滤什么?用户产品还是产品?
  • 我正在按产品关系属性值过滤 UserProduct。我最初的做法是正确的,正如我在问题更新中指定的那样,它是破坏过滤的 orWhere 语句。
  • 请重新托盘
【解决方案2】:

我刚刚删除了where("is_featured", 1),并用where("is_hidden_from_latest", 0) 替换了它,因为无论如何我将结果按is_featured 排序。

whereHas() 子查询可以正常工作。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    相关资源
    最近更新 更多