首页 > 解决方案 > 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.

标签: mysqllaraveleloquentone-to-one

解决方案


首先,您放置了错误的参数。

$this->belongsTo('App\Models\Policy', "FK", "PK");

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

对于nullpolicy_id 的值,您可以使用withDefault();

public function policy() {
    return $this->belongsTo('App\Models\Policy','policy_id', 'id')->withDefault([
        'name' => 'test'
    ]);;
}

推荐阅读