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

标签 php mysql laravel laravel-5.1

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

相关文章:

Mysql查询从和到

mysql - Laravel-4 本地服务器上用户的实时内容更新

php - 三个表和 belongsTo() 函数的 Laravel Eloquent 关系映射问题

php - 在 laravel 中显示数据库中的选定选项

php - foreach循环中的mysql更新

php - MySQL 查询不工作。没有给出预期的结果

php - 单行的详细信息按钮 [PHP,MYSQL]

mysql - 比较两个表的值与一个表中的多个日期

PHP 代码不会更新数据库

php - 写出 html 而不是动态创建元素时出现 Javascript 错误