为不同的查询克隆 eloquent 个模型

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