Laravel,关系问题

问题描述 投票:0回答:2

这是我的第一个Laravel项目,我必须做一个LMS(学习管理系统)。我有一个课程表和一个用户表。

这是我的控制器代码:

public function afficheFormation($id)
    {
        $formation = DB::table('formation')->select('formation.*')->where('id', $id)->first();
        $cours = DB::table('Course')->join('Course_formation', 'course_id', '=', 'Course.id')

            ->select('Course.*')->where('formation_id', $id)->get();


        return view('formation', compact('formation', 'cours'));
    }

这是我的查看代码:

<tr>
 <td class="align-middle">{{ $cours->name }}</td>
 <td class="align-middle">{{ $cours->level}}</td>    
 <td class="align-middle">{{ $cours->user() }}</td>
</tr>
@endforeach
@endif

课程有一个外键Professor_id,我想显示创建课程的用户名,但有一些错误

这是我的课程模型:

class Course extends Model 
{

    protected $table = 'cours';
    public $timestamps = true;

    protected $fillable = [
        'name', 'lien', 'type', 'level', 'theme_id', 'prof_id'
    ];

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

这是我的用户模型:

class User extends Authenticatable
{
    use Notifiable;

    protected $table = 'users';
    public $timestamps = true;

    protected $fillable = [
        'pseudo', 'email', 'password', 'name', 'prenom', 'image'
    ];

    public function roles()
    {
          //return $this->belongsToMany('App\Models\Role', 'user_role', 'user_id', 'role_id');
          return $this->belongsToMany(Role::class);
    }

    public function cours()
    {
        return $this->belongsToMany('App\Models\Course', 'professor_id', 'id');
    }
}

感谢您的帮助。

laravel eloquent--relationship
2个回答
0
投票

在控制器中尝试这个

$cours = Course::with('cours')
                 ->where('id' , $id)
                 ->get(); 

和课程模型

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

在用户模型中

public function cours() {
          return $this->belongsToMany('App\model\Course', 'prof_id', 'id');
    }

关系取决于您,但看起来像这样。希望它会有所帮助


0
投票

编辑

感谢Abir,我找到了一些改变的方法。

如果我理解的话,Cours :: with('user')是在模型Cours中调用函数user()的一种方式。这是对的吗?

public function afficheFormation($id)
    {
        $formation = DB::table('formation')->select('formation.*')->where('id', $id)->first();
        $cours = Cours::with('user')
            ->join('Cours_formation', 'cours_id', '=', 'Cours.id')
            ->select('cours.*')->where('formation_id', $id)->get();

        return view('formation', compact('formation', 'cours'));
    }

在视图中,我们有以下代码:

@if(count($cours)> 0 )
@foreach($cours as $cours)
<tr>
  <td class="align-middle">
  {{ $cours->name }}
  </td>
  <td class="align-middle">
  {{ $cours->niveau}}
  </td>    
  <td class="align-middle">
  {{ $cours->user->name}}
  </td>
</tr> @endforeach
@endif 

对于库尔斯模型:

public function user()
    {
        return $this->belongsTo(User::class, 'prof_id', 'id');
    }

以及用户模型的结尾:

public function cours()
    {
        return $this->hasMany(Cours::class);
    }

谢谢。

© www.soinside.com 2019 - 2024. All rights reserved.