2017-02-11 46 views
0

是否可以合併一個雄辯的集合與查詢生成器?在Laravel中合併雄辯集合和查詢?

在這個例子中,我有3個表格。圖片表格,標籤表格和圖片標籤表格。我在圖像和標籤模型中也有雄辯的關係。

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

本質只是採取查詢(返回一個來自圖像表的n數組)和集合(它也從圖像表返回數組),對結果進行組合和排序。

這可能嗎?

編輯2:

當試圖傘兵的新的應答,則出現下列錯誤:

FatalThrowableError在SearchController.php管線98:調用一個成員 函數整數

指定者()

回答

2

試試這個:

$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); 
+0

更新了我的文章。我想指出圖像表和標籤表不直接引用對方。然而,這些images_tag表的確如此。這些列被稱爲tag_id和image_id。你的帖子試圖從圖片表中獲取tag_id,而不是數據透視表。 –

+0

我的圖像表的名稱確實是「圖像」,其主鍵是「id」。但是,我仍然遇到錯誤。我更新了我的帖子。 –

+0

它的工作原理!謝謝。 –