将 eloquent 集合与 Laravel 中的查询合并?

Merge eloquent collection with query in Laravel?

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

在这个例子中,我有 3 个 table。图片 table、标签 table 和 images_tag table。我在图像和标签模型中也有 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);     

本质上只是获取查询(returns 来自图像 table 的数组)和集合(returns 来自图像 table 的数组), 合并并排序结果。

这可能吗?

编辑 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);