我尝试使用关系从模型中检索某些结果,并尝试对该关系应用某些过滤器。
以下是模型:
<?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()
语句。
答案 0 :(得分:0)
试试这种方式
$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();
答案 1 :(得分:0)
我刚刚删除了where("is_featured", 1)
并将其替换为where("is_hidden_from_latest", 0)
,因为我总是按is_featured
排序结果。
whereHas()
子查询正常工作。 :)