无法访问hasMany型号

时间:2019-03-12 06:15:29

标签: laravel laravel-5 eloquent

模型 Joindraw.php

class Joindraw extends Model
{
    protected $table = 'joindraw';

    public function user() {
        return $this->belongsTo('App\Models\User', 'user_id');
    }
}

模型 User.php

class User extends Authenticatable
{
    public function joindraw() {
        return $this->hasMany('App\Models\Joindraw');
}

IndexController.php

public function details(Request $request, $id, $fortune_code=null)
{
    $joindraw_participants = Joindraw::where('product_id', $id)->get();
}

View.blade.php

@forelse($joindraw_participants as $record)
    {{ $record->user->mobile }}

我遇到错误:

  

从非对象获取属性。

如何从joindraw访问子模型?反之亦然?

1 个答案:

答案 0 :(得分:0)

您的控制器:

public function details(Request $request, $id, $fortune_code=null)
{
    $joindraw_participants = Joindraw::where('product_id', $id)->get();
}

还有您的刀片服务器

@foreach($joindraw_participants as $record) 
  {{ $record->user->mobile }}
@endforeach