无法使用hasOne关系来放置限制

时间:2019-04-15 05:25:30

标签: laravel eloquent model has-one

我在模型“成员”和“贷款”之间有一个关联。我抛出“试图获取非对象错误的属性

我已经尝试过hasMany,并且一切正常,但是必须在hasOne中,没有限制可以停止向成员发放多笔贷款。

Member.php

use Illuminate\Database\Eloquent\Model;

class Member extends Model
{
    protected $fillable=['name','address','phone']; 

    public function loan()
    {
        return $this->hasOne(Loan::class,'member_id','id');
    }

    public  function savings()
    {
        return $this->hasMany(Saving::class,'member_id','id');
    }
}

Loan.php

use Illuminate\Database\Eloquent\Model;

class Loan extends Model
{
    protected $fillable = [
        'amount',
        'interest',
        'status',
        'member_id',
        'loan_type_id',
        'interest_type_id',
        'loan_payment_type_id'
    ];

    public function member()
    {
        return $this->belongsTo(Member::class,'member_id','id');
    }
}

member.blade.php

<td>{{$member->name}}</td>
<td>{{$member->address}}</td>
<td>{{$member->phone}}</td>
<td>
    <a href="{{route('deletemember').'/'.$member->id }}">Delete</a>
    <a href="{{route('editmember').'/'.$member->id }}">Edit</a>
</td>
<td>
    {{$member->loan->amount}}
</td>

2 个答案:

答案 0 :(得分:1)

也许您的所有成员都没有贷款。这就是为什么显示错误,尝试在回显之前进行检查,

  <td>
   @if($member->loan)  // add this line code
     {{ $member->loan->amount }}
   @endif  // add this line code
  </td>

答案 1 :(得分:-1)

尝试

{{$member->loan['amount']}}