【问题标题】:How to access `object` data better than `$collection[0]->object`如何比 `$collection[0]->object` 更好地访问 `object` 数据
【发布时间】:2016-04-07 13:22:47
【问题描述】:

我是 PDO PHP 的新手,我确信我没有以有效的方式编写它。我一直在为如何从collection 中获取object 数据而苦苦挣扎,而我这样做的方式很丑陋。

例如,我有两个表work_ordersaircraft。我想通过使用我的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


【解决方案1】:

您可以使用整个代码来代替:

// Temporary injection
$order_number = '502';

// Use the aircraft_id to find get the aircraft data
$aircraft = $aircraft->findOrFail($workorder->select('aircraft_id')->findOrFail($order_number)->aircraft_id);

代替:

->where('id', $order_number)->get();

你可以在这里使用

->find($order_number)(或更好的->findOrFail($order_number) 以确保记录存在并且您不会对null 采取任何操作) - 它只会采用具有给定ID 的第一条记录。

现在您只需访问属性aircraft_id 就可以了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多