Clone eloquent models for different requests
Sorry for changing this question (to everyone who answered here). The question was actually wrong.
$query = User::find(1)->books(); //books() is "return $this->hasMany('Book');"
$query_for_counting_history_books = clone $query;
$query_for_counting_geography_books = clone $query;
$number_of_history_books = $query_for_counting_history_books->where('type', '=', 'history')->count();
$number_of_geography_books = $query_for_counting_geography_books->where('type', '=', 'geography')->count();
$books = $query->paginate(10);
I want $ books to be requested like:
SELECT * FROM books WHERE user_id = 1 limit 10;
But his conclusion:
SELECT * FROM books WHERE user_id = 1 and type = "history" and type = "geography" limit 10;
- Am I missing something about Clone here?
- What needs to be done for this solution?
source to share
Since $ query is a HasMany instance, cloning should be done as:
$ query_for_counting_history_books = clone $ query-> getQuery ();
$ query_for_counting_geography_books = clone $ query-> getQuery ();
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Relations/HasOneOrMany.html#method_getQuery
source to share
Not sure why yours is clone()
n't working, but try this:
$query = User::where('confirmed', '=', '1');
$query_for_counting_male = $query->replicate();
$query_for_counting_female = $query->replicate();
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_replicate
source to share