简体   繁体   English

laravel-三对多关系

[英]laravel - 3 steps relation by many to many

I have 3 tabels: users, teachers And posts. 我有3个表格:用户,教师和帖子。

users : 用户
id - integer id-整数
name - string 名称-字符串

teachers : 老师
id - integer id-整数
teacher_id - integer Teacher_id-整数
user_id - integer user_id-整数
name - string 名称-字符串

posts : 帖子
id - integer id-整数
user_id - integer user_id-整数
title - string 标题-字符串


User Model: 用户模型:

class User extends Model
{
  public function teachers()
  {
    return $this->hasMany('App\Teacher');
  }
}


Teacher Model: 教师模式:

class Teacher extends Model
{
  public function posts()
  {
    return $this->hasMany('App\Post', 'user_id','teacher_id');
  }
}


? Question is How can I use sth like this: 问题是我该如何使用……

$user = User::find(1);
$teacher_posts = $user->teachers()->posts

I'm sort of new to laravel but here is my take. 我是laravel的新手,但这是我的看法。

What I have realized is that typically your many to many relationships will require a pivot table. 我已经意识到,通常您的多对多关系将需要一个透视表。

users :(id, name) 用户 :(id,名称)

teachers :(id, teacher_id, name) 教师 :(id,teacher_id,姓名)

teacher_users :(id, user_id, teacher_id) 教师用户 :(id,user_id,teacher_id)

posts :(id, user_id, title) 帖子 :(id,user_id,title)

And your Eloquent models will look like this. 而且您的口才模型将如下所示。

class User extends Model
{
  public function teachers()
  {
    return $this->belongsToMany('App\Teacher');
  }

  public function posts()
  {
    return $this->hasMany('App\Post');
  }
}


class Teacher extends Model
{
  public function users()
  {
    return $this->belongsToMany('App\User');
  }
}

$user = User::find(1);
$user_posts = $user->posts();

Check out the documentation here for more details 在此处查看文档以获取更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM