[英]Clone eloquent models for different queries
很抱歉修改此問題(對所有已在此處回答的人)。 這個問題實際上是錯誤的。
$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);
我希望查詢$ books:
SELECT * FROM books WHERE user_id = 1 limit 10;
但它的輸出是:
SELECT * FROM books WHERE user_id = 1 and type =“history”and type =“geography”limit 10;
不確定為什么你的clone()
不工作 - 但試試這個:
$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
由於$ query是HasMany的實例,因此克隆應該如下:
$ 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.