【问题标题】:Laravel ORM method vs attributeLaravel ORM 方法与属性
【发布时间】:2014-08-18 15:24:43
【问题描述】:

在处理 Laravel 的关系时,我经常使用这样的东西:

User::where(...)
      ->first()
      ->securityQuestions()
      ->take(2)
      ->orderBy(DB::raw('RAND()'))
      ->get();

注意使用securityQuestions() 而不是securityQuestions,否则会引发错误:

Missing argument 1 for Illuminate\Support\Collection::get()

现在,在其他部分我可以使用:

User::where(...)
      ->first()
      ->securityQuestions
      ->contains(...)

注意使用securityQuestions 而不是securityQuestions()

我的猜测是,为了从数据库中检索内容(并继续链接wheres 和内容),您必须在属性具有不可变结果集时使用该方法。有谁知道这是否正确?

【问题讨论】:

  • 什么是安全问题?自定义函数?还是表格列?
  • @TheShiftExchange - 如果我猜的话,用户与 SecurityQuestion 是一对多的关系。
  • 您能否尝试使用 DB::getQueryLog(); 打印在后台为这两个查询生成的 SQL?查看此链接stackoverflow.com/a/19085511/3007014。然后你可以比较有什么不同。
  • @TheShiftExchange 引用security_questions 表的模型,与users 表的多对多关系。

标签: php laravel-4


【解决方案1】:

天哪,4 年后。

基本上->securityQuestions()Eloquent collection->securityQuestionsLaravel collection

前者可以继续查询数据库,后者不能。对前者的转换会影响数据库,而后者不会。

是的,我是对的:

我的猜测是,为了从数据库中检索内容(并保持链接 wheres 和内容),您必须在属性具有不可变结果集时使用该方法。有谁知道这是否正确?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-21
    • 2018-01-09
    • 2017-07-16
    • 2015-02-09
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 2012-05-05
    相关资源
    最近更新 更多