【问题标题】:Laravel 4: How to remove `limit 1` restriction from Find() in Eloquent?Laravel 4:如何从 Eloquent 中的 Find() 中删除 `limit 1` 限制?
【发布时间】:2013-05-23 13:43:15
【问题描述】:

我想检索属于一个 author_id(在本例中为 author2)的所有任务详细信息(task_title 等)。

测试表

author_id  task_id
author2    task_1
author2    task_2

任务表

task_id task_title 
task_1  task_title_1
task_2  task_title_2

作者表

author_id author_name
author_2  authorTwo

模型测试.php

public function tasks()
{  
return $this->belongsTo('Task','task_id');  
}

TestsController.php

public function index()  
{  
   $test=Test::find('author2')->tasks()->get();  
   return View::make('tests.index', compact('tests'));  
}

和查询SQL:

select * from `tests` where `author_id` = 'author2' limit 1
select * from `tasks` where `tasks`.`task_id` = 'task1'

但实际上在任务表中,与作者 2 相关的值不止一个(在本例中为任务 1 和任务 2),但由于 sql 仅说明了任务 1。

如何取消限制 1 的限制以检索属于作者 2 的所有任务?

【问题讨论】:

    标签: php laravel laravel-4 eloquent


    【解决方案1】:

    这有多个问题。主要有:

    • 您使用了错误的多对多关系,请查看belongsToMany()
    • 您似乎正在尝试查找不受支持的复合键
    • Find 旨在仅获取一条记录,并且不限制关系的结果集。如您的 SQL 所示,您并没有将任务限制为一项,而是在限制测试。当您需要获取多条记录时,请结合使用 get()where()

    这里是帮助您入门的文档链接 - http://four.laravel.com/docs/eloquent

    【讨论】:

      【解决方案2】:

      Test::where("author_id","=","author2")->get()

      顺便说一句,您不应该将find 用于非主键的任何内容。这是 find 的目的:它假设它搜索的键是主自动增量(即唯一),因此它获取一个项目

      【讨论】:

      • 谢谢!现在我可以通过编码Test::with('tasks')->where("author_id","=","author2")->get() 来检索所有相关任务
      • @JackpotK:是的;但是,您可能想研究人际关系。为自己定义一个具有多对一关系的 author() 函数。
      • 好的,你能告诉我如何定义一个 author() 函数吗?我刚刚发现的另一个问题,虽然 sql 更改为 select * from tests` where author_id = 'tester2` select * from tasks` where tasks.task_id in ('task1', 'task2')` 当我尝试使用 $tests->task_id $tests->task_task_title 显示任务详细信息,只有 task_id 正确显示但 task_title 为空。
      • public function author() { return $this->belongs_to("AuthorModel","author_id"); } 如果它的工作方式与 L3 相同。你需要一个 Author 模型。
      • 假设我已经通过 $tests 值来查看,如果我可以使用 $tests->task_title, $tests->task_id (这实际上来自任务表)。但它无法显示task_title。 task_id 是tasks_table 的主键。你知道怎么解决吗?
      猜你喜欢
      • 1970-01-01
      • 2012-12-26
      • 1970-01-01
      • 2017-10-09
      • 2014-12-06
      • 2013-05-27
      • 2011-12-13
      • 1970-01-01
      • 2013-03-13
      相关资源
      最近更新 更多