是否可以将 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/