Laravel雄辩的关系多对一不起作用

时间:2019-01-12 17:56:11

标签: laravel eloquent foreign-keys relationship

[Laravel 5.7]我在两个实体(用户,语音)之间有一个多对一关系,并且在我的项目中不起作用。

用户迁移:

Schema::create('users', function (Blueprint $table) {
   $table->increments('id');
   $table->string('n_name');
   $table->string('n_photo');
   $table->string('n_gender');
});

语音迁移:

  Schema::create('voices', function (Blueprint $table) {
     $table->increments('id');
     $table->string('voice');
     $table->integer('n_id')->unsigned();
     $table->foreign('n_id')->references('id')
      ->on('users')->onDelete('cascade');
  });

用户模型:

class User extends Model
{
   public function voices(){
      return $this->hasMany(Voice::class);
   }
}

语音模型:

class Voice extends Model
{
   public function user(){
      return $this->belongsTo(User::class, 'n_id');
   }
}

在我的控制器中,函数“索引”如下所示:

   public function index()
   {
      $user= User::all();
      $voices = $user->voices()::get(); -- error <described below>

      return view('index', compact('user', 'voices'));
   }

当我想获取每个用户的声音时,它给我一个错误: “方法Illuminate \ Database \ Eloquent \ Collection :: voices不存在。”

我的视图如下:

@if($n->voices)
  @foreach($n->voices as $voice)
    <audio controls src="voices/{{$voice->voice}}"></audio><br/>
  @endforeach
@endif

我希望我很好地解释了这个问题,并等待解决方案。

2 个答案:

答案 0 :(得分:0)

很抱歉,我上一封邮件中有您遇到的问题。

您无法在COLLECTION实体上获取关系。

您的控制器应如下所示:

public function index()
{
    $user= User::with('voices')->get();

    return view('index', compact('user'));
}

您的刀片应该看起来像:

@foreach($users as $user)
    @foreach($user->voices as $voice)
    <audio controls src="voices/{{$voice->voice}}"></audio><br/>
  @endforeach
@endif

它对您有用吗?

答案 1 :(得分:0)

尝试使用您的控制器:

$users = User::with('voices')->get();

我以这种方式使用它,它对我来说正常工作。