samedi 11 février 2017

Merge eloquent collection with query in Laravel?

Is it possible to merge an eloquent collection with a query builder?

In this example, I've got 3 tables. An images table, a tag table, and an images_tag table. I also have eloquent relationships in both the Images and Tag models.

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

What I'd like to do is something like this:

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

Essentially just taking the query (which returns an array from the images table), and the collection (which also returns an array from the images table), combine and sort the results.

Is this possible?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire