【发布时间】: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_status 和parent_child。
有什么我做的不对吗?
更新:似乎游戏破坏者是最后这两个where() 语句:
....
->where("is_featured", 1)
->orWhere("is_hidden_from_latest", 0)
....
更具体地说是orWhere() 声明。
【问题讨论】:
-
只是出于好奇。为什么你们的关系会出现双重反弹?
-
使用字符串定义命名空间时,string escaping rules可能适用,为避免这种情况,建议使用双反斜杠。
-
反斜杠用于访问命名空间,我不明白为什么要加倍。
-
因为在 php 中包含命名空间,就像在许多其他支持命名空间的语言中一样,不需要引号,但在这种情况下,我使用字符串来定义相关模型,因为在某些情况下反斜杠可能是逃脱使用反斜杠更安全。不过,这不是必需的。
-
你已经解决了这个问题吗?
标签: php mysql laravel eloquent