【问题标题】:How to use laravel relations when there is DB::select()?有 DB::select() 时如何使用 laravel 关系?
【发布时间】:2018-04-22 08:30:45
【问题描述】:

这是我的代码:

$guarantee_tickets =  DB::select("(select ga.id, '' as unique_product_id, ga.user_id, ga.submit_time, '' as title, ga.description, '' as  tracking_code, '' as closed, '' as close_date, ga.isAdminNote from guarantee_tickets_answers ga where guarantee_tickets_id = $request->id order by ga.id desc)
                                   union all
                                  (select gt.id, gt.unique_product_id, gt.user_id, gt.submit_time, gt.title, gt.description, gt.tracking_code, gt.closed, gt.close_date, '' from guarantee_tickets gt where id = $request->id)");

还有这个:

dd($guarantee_tickets->user->name);

抛出:

未定义属性:stdClass::$user

我该如何解决?


注意到我在 guarantee_ticketsguarantee_tickets_answers 模型中都有这个:

public function user()
{
    return $this->hasOne(User::class, 'id', 'user_id');
}

【问题讨论】:

  • DB::Select 没有使用 Eloquent,它正在执行原始查询。
  • 你不能有一个雄辩的集合有两个不同的模型。如果你只想要一个模型,你可以使用Model::hydrateRaw()而不是DB::select()

标签: php mysql laravel orm relational-database


【解决方案1】:

当您使用DB::Select 执行查询时,您正在对数据库执行原始 SQL 查询。您将收到stdClass 的实例,该实例具有来自数据库的属性。你可以阅读更多关于这个here的信息。

如果您希望能够访问这些关系,那么您需要执行 Eloquent 查询来加载数据。

【讨论】:

    猜你喜欢
    • 2018-09-05
    • 2017-01-16
    • 2015-07-27
    • 2020-01-08
    • 1970-01-01
    • 2017-10-20
    • 2015-10-27
    • 2014-12-18
    • 1970-01-01
    相关资源
    最近更新 更多