【发布时间】:2020-01-31 06:03:25
【问题描述】:
我正在构建一个标签过滤器。到目前为止,我有一个查询返回已向查询提供标签或艺术家的产品。由于标签和作者过滤器的 if 语句一团糟,我不得不将其分解。该查询正在运行,并为我提供了我在选择中明确要求的所有结果。但我需要让它急切地加载每个结果关系。我尝试将 with('tags') 放入组合中,但它只是分配一个空集合。我很确定我在某个地方需要 with('tags') 方法,但我不确定在哪里。或者我可能完全走错了路。我不必将自己局限于标签关系(一对多的关系,所以我不能将它包含在查询结果中)。
这是我的查询,$tags 和 $artists 是标签和艺术家的列表。
if (count($tags)) {
$tagged_products = DB::table('product_tags')
->whereIn('product_tags.tag', $tags)
->groupBy('product_tags.product_uuid')
->select('product_tags.product_uuid')
->havingRaw('count(product_tags.tag) = '.count($tags));
} else {
$tagged_products = DB::table('product_tags')
->select('product_tags.product_uuid');
}
if (count($artists)) {
$artist_products = DB::table('profiles')
->whereIn('profiles.attribution', $artists)
->select('profiles.user_uuid');
} else {
$artist_products = DB::table('products')->select('products.user_uuid');
}
$results = Product::with('tags')
->join('profiles', 'products.user_uuid', '=', 'profiles.user_uuid')
->whereIn('products.uuid', $tagged_products)->whereIn('products.user_uuid',
$artist_products)->get();
$results->dd();
如果我查询单个产品记录,我可以很好地获取标签关系的值。
这里是模型:
class Product extends Model
{
protected $fillable = [
'title', 'cost', 'description', 'thumbnail'
];
protected $primaryKey = 'uuid';
public $incrementing = FALSE;
public function tags(){
return $this->hasMany('App\ProductTag', 'product_uuid', 'uuid');
}
public function profile(){
return $this->hasOne('App\Profile', 'user_uuid', 'user_uuid');
}
}
class Profile extends Model
{
protected $fillable = [
'attribution', 'links', 'description', 'user_uuid',
];
protected $primaryKey = 'user_uuid';
public $incrementing = FALSE;
public function projects()
{
return $this->hasMany('App\Project', 'user_uuid', 'user_uuid');
}
}
class ProductTag extends Model
{
protected $fillable = [
'product_uuid', 'tag',
];
//
public function product()
{
return $this->belongsTo('App\Product', 'product_uuid', 'uuid');
}
}
【问题讨论】:
-
能否请您也提供我们的模型?
标签: laravel eloquent laravel-6