【问题标题】:How to implement hasOne with optional relationship如何实现具有可选关系的 hasOne
【发布时间】:2020-02-06 06:17:40
【问题描述】:

我有一张这样的客户表

id
name

这样的另一个表策略

id
policy_name

还有另一个像这样的表 policy_customer

id 
customer_id
policy_id

在我的客户模型中我是这样写的


    protected $appends = ['policy_customer'];

    public function policy_customer() {
        return $this->hasOne('App\Models\PolicyCustomer', "customer_id", "id");
    }

    public function getPolicyCustomerAttribute(){
        return $this->policy_customer()->firstOrFail();
    }

在 PolicyCustomer 模型中


    public function policy() {
        return $this->belongsTo('App\Models\Policy', "policy_id", "id");
    }

    public function customer() {
        return $this->belongsTo('App\Models\Customer', "customer_id", "id");
    }

所有客户可能没有与其帐户相关联的政策。 当我查询 Customer::get() 时没有问题。但是,如果我尝试将此作为控制器的响应返回,则会收到如下错误:


[2020-02-06 06:11:47] local.ERROR: Illuminate\Database\Eloquent\ModelNotFoundException: No query results for model [App\Models\PolicyCustomer]. in D:\Projects\others\jayhawker\backend\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Builder.php:454
Stack trace:
#0 D:\Projects\others\jayhawker\backend\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php(23): Illuminate\Database\Eloquent\Builder->firstOrFail()
#1 D:\Projects\others\jayhawker\backend\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Relations\Relation.php(385): Illuminate\Database\Eloquent\Relations\Relation->forwardCallTo(Object(Illuminate\Database\Eloquent\Builder), 'firstOrFail', Array)
#2 D:\Projects\others\jayhawker\backend\app\Models\Customer.php(41): Illuminate\Database\Eloquent\Relations\Relation->__call('firstOrFail', Array)
#3 D:\Projects\others\jayhawker\backend\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php(454): App\Models\Customer->getPolicyAttribute(NULL)
#

如果我从 Customer 模型中删除 getPolicyCustomerAttribute 函数,它不会引发异常。 我错过了什么吗?

【问题讨论】:

  • 你的数据库看起来像many-to-many。
  • 保单和客户是什么关系?
  • 你可以使用many-to-many关系。
  • 我也尝试了很多。它仍然抛出错误。

标签: laravel eloquent orm


【解决方案1】:

只需删除您的 getPolicyCustomerAttribute 访问器方法。所有关系方法都会自动提供一个同名的属性,该属性将包含关系的结果。

也就是说,$customer->policy_customer 将包含相关的 PolicyCustomer 实例,如果没有相关记录,则为 null。

$customer->policy_customer === $customer->policy_customer()->first();

【讨论】:

  • 如果我删除 getPolicyCustomerAttribute 错误将消失,但对象不在生成的 json 中
猜你喜欢
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-30
  • 2020-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多