【问题标题】:Trouble Retrieving Proper Results with Laravel Eloquent Relations使用 Laravel Eloquent 关系无法检索正确的结果
【发布时间】:2015-03-26 15:49:59
【问题描述】:

我在使用 Eloquent 关系检索特定结果集时遇到问题。

型号:
Application(table: application) [id, title, active]
问题(表:问题)[idapplication_id、question_text、helper_text、question_type]
QuestionType(table: question_type) [id, type]
粗体 = 主键,斜体 = 外键

关系:
一个Application 有多个Questions
许多Questions 可以属于一个Application

一个Question 有一个QuestionType(由 question_type FK 引用)
一个QuestionType 可以属于多个Questions(通过引用它的id 作为question_type)

QuestionType 是一个静态表,永远不会添加或删除值,但类型属性可以更改。

我希望能够做这样的事情:

$application = Application:find($application_id);  
$questions = $application->questions()->get();

并将 question_type 替换为从 QuestionType 模型中提取的适当类型。

我浏览了 Laravel 和 Eloquent 文档,在 IRC 上提问,并浏览了其他 StackOverflow 文章,但找不到有用的答案。我认为让我失望的是我的非常规外键question_type,在我的Question 表中。我有一次把它搞定了,异常 question_type 被替换为 QuestionType 数组(这不起作用)。

【问题讨论】:

  • 你可以打电话给你的领域question_type_id吗?这可能会消除一些混乱并使事情更自然地工作。
  • 我可以,但问题是我需要该 question_type 用于其他目的(主要用于决策逻辑)。是否可以将“类型”附加到问题结果上而不是用它替换 question_type?

标签: php mysql laravel eloquent relationships


【解决方案1】:

我说先将此关系添加到Question

public function type(){
   return $this->belongsTo('QuestionType', 'question_type');
}

然后像平常一样使用它:

$question = Question::find(1);
$question->type;

对于应用程序的所有问题(急切加载)

$application = Application:find($application_id);  
$questions = $application->questions()->with('type')->get();

编辑

要仅获取类型的实际名称(名为type 的列),您可以添加attribute accessor。然而,命名变得有点困难。如果您真的不想将外键名称更改为question_type_id,我建议这样做:

public function typeRelation(){
    return $this->belongsTo('QuestionType', 'question_type');
}

public function getTypeAttribute(){
    if(is_null($this->typeRelation)) return null;
    return $this->typeRelation->type;
}

属性访问器允许您使用$question->type 并直接获取相关模型的属性。急切加载时不要忘记调整关系名称:with('typeRelation')

【讨论】:

  • 我喜欢这个,它消除了属性和关系之间的命名冲突。
  • 是的。另外,在我看来,拥有$question->questionType 是非常多余的。我更喜欢$question->type :)
  • 啊,这更接近了!现在它返回这个(通过遍历集合): {"id":2,"type":"Short Answer","created_at":"2015-01-26 20:33:29","updated_at":" 2015-01-26 20:33:29"} 有没有办法像 $q->type 一样访问它并只收到“Short Answer”?
  • 这不是你想要的吗?还是您只想要实际名称? (type)
  • 在访问器中添加对null 的检查。在这种情况下可能没有必要(我想一个问题没有类型就不可能存在),但是当您循环通过questions 并且有一个没有相关模型时,这是一种让自己头疼的好习惯。跨度>
猜你喜欢
  • 2013-09-28
  • 2021-01-26
  • 2021-11-17
  • 2013-01-30
  • 2018-06-11
  • 1970-01-01
  • 1970-01-01
  • 2019-08-24
  • 2019-08-17
相关资源
最近更新 更多