[英]Laravel: How do I create the relationship and which one do I use?
I have the database structure that have a classes
table, a users
table and users_classes
table that matches the other two, because a user can belong to multiple classes. 我的数据库结构具有一个
classes
表,一个users
表和一个与其他两个表匹配的users_classes
表,因为一个用户可以属于多个类。 I have a problem now. 我现在有问题。 I have code like this:
我有这样的代码:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Classes extends Model
{
protected $table = 'classes';
public function students()
{
}
}
And I want to be able to access the students of the class by typing $class = Classes::find(1)
and then $class->students
to access the students. 而且我希望能够通过键入
$class = Classes::find(1)
并然后通过$class->students
访问$class->students
来访问班级的学生。 How do I define the relationship without using the query builder? 如何在不使用查询生成器的情况下定义关系? I want to use eloquent.
我要用口才。 Im a noobie in Laravel pls dont downvote.
我是Laravel的noobie,请不要投票。
You use a belongsToMany
relation. 您使用一个
belongsToMany
关系。
If your users_classes
table has the fields user_id
and class_id
you can do the following: 如果您的
users_classes
表具有字段user_id
和class_id
,则可以执行以下操作:
public function students()
{
return $this->belongsToMany(Student::class, 'users_classes', 'class_id', 'user_id');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.