gpt4 book ai didi

php - 在 Laravel 中将 Eloquent 集合与查询合并?

转载 作者:行者123 更新时间:2023-11-29 07:04:40 25 4
gpt4 key购买 nike

是否可以将 eloquent 集合与查询生成器合并?

在此示例中,我有 3 个表。图像表、标签表和 images_tag 表。我在图像和标签模型中也有 Eloquent 关系。

Tag.php:

class Tag extends Model {

protected $table = 'tags';

public $timestamps = false;

protected $fillable = [
'tagname',
];

public function Images() {
return $this->belongsToMany('CommendMe\Models\Images');
}

}

Images.php:

public function tags() {
return $this->belongsToMany('CommendMe\Models\Tag');
}

我想做的是这样的:

$tag = Tag::where('tagname', $query)->first();

$imagesWithTag = $tag->images;

$imagesWithoutTag = Images::where('title', 'LIKE', "%{$query}%");

$images = $imagesWithTag + $imagesWithoutTag
->whereIn('mature', [0, $mature])
->where('created_at', '>=', Carbon::now()->subHours($withinHours))
->orderBy($orderByString, 'desc')
->Paginate(50);

本质上只是获取查询(从图像表返回一个数组)和集合(也从图像表返回一个数组),对结果进行组合和排序。

这可能吗?

编辑2:

尝试Paras的新答案时,出现以下错误:

FatalThrowableError in SearchController.php line 98: Call to a member function toArray() on integer

最佳答案

试试这个:

$tag = Tag::where('tagname', $query)->first();
$imageIds = $tag->images()->select('images.id')->get()->pluck('id')->toArray(); // assuming your images table name is "images" and primary key name is "id"
$images = Images::where(function($q) use($imageIds, $query) {
$q->whereIn('id', $imageIds)
->orWhere('title', 'LIKE', "%{$query}%");
})->whereIn('mature', [0, $mature])
->where('created_at', '>=', Carbon::now()->subHours($withinHours))
->orderBy($orderByString, 'desc')->paginate(50);

关于php - 在 Laravel 中将 Eloquent 集合与查询合并?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42180817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com