【问题标题】:how to check exist relation in eloquent query?如何检查 eloquent 查询中存在的关系?
【发布时间】:2017-11-15 23:47:31
【问题描述】:

我正在使用laravel 多态关系。

车模型:

public function  objectable()
{
    return $this->morphTo();
}

指令模型:

public function cartable()
{
    return $this->morphMany('PTA_OIMS\Cartable', 'objectable');
}

报告模型:

public function reports()
{
    return $this->morphMany('PTA_OIMS\Cartable', 'objectable');
}

我的指令表有额外的相关表,称为指令日志。

但在报告表中,这种关系不存在。 当我的对象被报告时,这个查询有错误。因为reports.report_logs 不存在。

$data = Cartable::where('id', '=', $cartableID)
    ->with('objectable')
    ->with('objectable.objectable_logs.attachment') //line error
    ->with('box.position')
    ->with('box.assign.staff')
    ->first();

return $data;

如果objectable_logs不存在,如何处理查询跳过行错误

【问题讨论】:

  • 一个if-声明?之后你可以继续这个链条

标签: laravel eloquent relationship


【解决方案1】:
$data = Cartable::with([
    'objectable',
    'objectable.objectable_logs.attachment',
    'box.position',
    'box.assign.staff'
])->find($cartableID);

return $data;  

如果attachmentobjectable_logs 表中的一列,它应该是这样的:

$data = Cartable::with([
    'objectable',
    'objectable.objectable_logs:objectable_id,attachment',
    'box.position',
    'box.assign.staff'
])->find($cartableID);

return $data; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-30
    • 2020-11-24
    • 2017-03-16
    • 2021-06-10
    • 2013-10-03
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多