Laravel 如何使用可选关系实现hasOne
我有一张这样的顾客桌Laravel 如何使用可选关系实现hasOne,laravel,eloquent,orm,Laravel,Eloquent,Orm,我有一张这样的顾客桌 id name 像这样的另一个表策略 id policy_name id customer_id policy_id protected $appends = ['policy_customer']; public function policy_customer() { return $this->hasOne('App\Models\PolicyCustomer', "customer_id", "id"); }
id
name
像这样的另一个表策略
id
policy_name
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();
}
还有另一位像这样的顾客
id
policy_name
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();
}
在我的客户模型中,我是这样写的
id
policy_name
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();
}
在客户模型中
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)
#
如果我从客户模型中删除getPolicyCustomerAttribute函数,它不会引发异常。
我遗漏了什么吗?只需删除您的
getPolicyCustomerAttribute
访问器方法。所有关系方法都会自动提供包含关系结果的同名属性
也就是说,$customer->policy\u customer
将包含相关的PolicyCustomer实例,或者如果没有相关记录,它将为null
$customer->policy_customer === $customer->policy_customer()->first();
您的数据库看起来像
多对多
。策略和客户之间的关系是什么?您可以使用多对多
关系。我也尝试了多对多。如果我删除getPolicyCustomerAttribute,错误将消失,但对象不在结果json中