【问题标题】:Laravel Eloquent Relationship Many-to-one is not workingLaravel 雄辩的关系多对一不起作用
【发布时间】:2019-06-07 07:28:00
【问题描述】:

[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

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

【问题讨论】:

    标签: laravel eloquent foreign-keys relationship


    【解决方案1】:

    抱歉我之前的消息,我刚刚收到了您遇到的问题。

    您无法获取实体集合上的关系。

    您的控制器应如下所示:

    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
    

    它对你有用吗?

    【讨论】:

    • @HassanInter 抱歉,修改了我的答案。
    • 它给了我另一个错误..说:这个集合实例上不存在属性 [voices]。
    • 再次修订,请注意您有一个用户集合而不是 1 个用户,因此您必须迭代每个用户,然后像上面的示例一样迭代每个语音。跨度>
    【解决方案2】:

    在您的控制器中尝试:

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

    我就是这样使用它的,它对我来说很好用。

    【讨论】:

      猜你喜欢
      • 2020-05-30
      • 2019-07-09
      • 2012-10-08
      • 2023-04-07
      • 2019-08-13
      • 1970-01-01
      • 2018-10-27
      • 2020-08-27
      相关资源
      最近更新 更多