mysql - hasOne with null-able in laravel not working
问题描述
I have a customer table which has a field called 'policy_id', where policy_id points to policy table. It is a null-able field, ie. Some customers may not have a policy. I have a relationship code like this in Customer.php
public function policy() {
return $this->hasOne('App\Models\Policy', "id", "policy_id");
}
But when I issue a search request I am getting error like this:
Illuminate\Database\Eloquent\ModelNotFoundException: No query results for model [App\Models\Policy]
If I modify the function like this:
public function policy() {
if ($this->getAttribute('policy_id')) {
return $this->hasOne('App\Models\Policy', "id", "policy_id");
} else {
return null
}
}
But I am getting an error like this:
Call to a member function getRelationExistenceQuery() on null
Here is my search code:
$c = new Customer();
return Customer::doesntHave('policy')->orWhere(function (Builder $query) use ($req) {
$query->orWhereHas('policy', function (Builder $query) use ($req) {
$p = new Policy();
$query->where($req->only($p->getFillable()))
->orWhereBetween("policy_period_from", [$req->policy_period_start_from, $req->policy_period_start_to])
->orWhereBetween("policy_period_to", [$req->policy_period_end_from, $req->policy_period_end_to])
->orWhereBetween("payment_date", [$req->payment_date_from, $req->payment_date_to]);
});
})->where($req->only($c->getFillable()))->get();
Am I missing something or are there any other ways to do this?
PS: While debugging the above search code is returning successfully, but the exception happening from somewhere inside Laravel after the prepareResponse call.
Thanks in advance.
解决方案
首先,您放置了错误的参数。
$this->belongsTo('App\Models\Policy', "FK", "PK");
public function policy() {
return $this->belongsTo('App\Models\Policy','policy_id', 'id');
}
对于null
policy_id 的值,您可以使用withDefault();
public function policy() {
return $this->belongsTo('App\Models\Policy','policy_id', 'id')->withDefault([
'name' => 'test'
]);;
}
推荐阅读
- kdb - 检查多个表中是否存在列
- apache-curator - 当馆长leaderlatch失去连接时发生了什么?
- highcharts - HighCharts 未按预期提供 x 轴值
- sql - 如何在 SQL SERVER 中明智地获取本周的数据
- css - flex: none 和 flex: 0 0 100% for mobile 之间的逻辑区别
- matlab - 如何从复杂的 Expression Maple/Matlab 构造只有两个变量和一个算术运算的子表达式?
- mongodb - 在 MongoDB 3.6 之前阅读您自己的写入一致性
- visual-studio-code - Tab 键在 Visual Studio 代码中不起作用
- c# - 如何修复错误弹出“类未注册”
- apache-zeppelin - Apache Zeppelin 错误本地 jar 不存在