【问题标题】:Clone eloquent models for different queries为不同的查询克隆 eloquent 模型
【发布时间】:2015-01-02 14:26:37
【问题描述】:

很抱歉修改了这个问题(致所有在此回答的人)。这个问题实际上是错误的。

$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" 限制 10 个;

  • 我在这里缺少关于 克隆 的内容吗?
  • 应该为这个解决方案做些什么?

【问题讨论】:

  • 它按预期工作。你能检查一下你的Illuminate\Database\Eloquent\Builder 是否实现了__clone() 方法吗?
  • @Demodave 不,绝对不是

标签: php laravel-4 eloquent


【解决方案1】:

不确定为什么您的 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

【讨论】:

  • Replicate 非常适合我的需求。克隆除主键之外的所有内容。谢谢!
【解决方案2】:

由于$query是HasMany的实例,所以克隆应该是这样的:

$query_for_counting_history_books = 克隆 $query->getQuery();

$query_for_counting_geography_books = 克隆 $query->getQuery();

http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Relations/HasOneOrMany.html#method_getQuery

【讨论】:

    猜你喜欢
    • 2019-04-24
    • 2015-03-03
    • 1970-01-01
    • 2012-01-05
    • 2012-10-19
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多