【发布时间】:2016-04-07 13:22:47
【问题描述】:
我是 PDO PHP 的新手,我确信我没有以有效的方式编写它。我一直在为如何从collection 中获取object 数据而苦苦挣扎,而我这样做的方式很丑陋。
例如,我有两个表work_orders 和aircraft。我想通过使用我的work_orders 表中的aircraft_id 字段从aircraft 表中获取飞机注册。
这是我的控制器中的内容:
// Temporary injection
$order_number = '502';
// Get the aircraft_id that corresponds to the work order supplied
$aircraft_id = $workorder->select('aircraft_id')
->where('id', $order_number)
->get();
// Assigned the aircraft_id to a variable
$aircraft_id = $aircraft_id[0]->aircraft_id;
// Use the aircraft_id to find get the aircraft data
$aircraft = $aircraft->findOrFail($aircraft_id);
我意识到上面写满了join(),我确实加入了它,但我是通过尝试解决我的问题而来到这里的……如果这有意义的话。
一直困扰着我的部分是我想要简单地输入$aircraft_id->aircraft_id,结果却遇到了同样的问题。
有没有更好的方法来构建我的查询,或者就是这样?
编辑
我的WorkOrder模特:
public function aircraft()
{
return $this->belongsTo(Aircraft::class);
}
【问题讨论】:
-
RE:如果我没记错的话,您可以使用
first()函数而不是get()来指示行索引的烦恼? -
我刚刚用
first()替换了get(),这确实消除了对[0]的需要,谢谢!
标签: php mysql pdo eloquent laravel-5.1