此设置应该可以帮助您。我试图使命名尽可能简单。
users id usernamechallenge_user user_id challenge_idchallenges id name topic_id category_idtopics id namecategories id name
定义口才模型
class User extends Eloquent { public function challenges() { return $this->belongsToMany('Challenge'); }}class Challenge extends Eloquent { public function users() { return $this->belongsToMany('User'); } public function topic() { return $this->belongsTo('Topic'); } public function category() { return $this->belongsTo('Category'); }}class Topic extends Eloquent { public function challenges() { return $this->hasMany('Challenge'); }}class Category extends Eloquent { public function challenges() { return $this->hasMany('Challenge'); }}使用您的口才模型…只是您可以做的一些事例。
// Collection of all Challenges by Topic nameTopic::with('challenges')->whereName($topic_name)->first()->challenges;// Collection of all Challenges by Category nameCategory::with('challenges')->whereName($category_name)->first()->challenges;// Collection of all Users by Challenge idChallenge::with('users')->find($challenge_id)->users;// Collection of Users with atleast 2 ChallengesUser::has('challenges', '>', 1)->get();// Attach Challenge to User$user = User::find($id);$user->challenges()->attach($challenge_id);// Assign a Topic to a Challenge$challenge = Challenge::find($challenge_id);$topic = Topic::find($topic_id);$challenge->topic()->associate($topic);$challenge->save();参考资料和建议阅读:
Laravel雄辩的关系
belongsTo
belongsToMany
hasMany
查询关系
Model::has()
渴望加载
Model::with()
动态属性访问关系解析
$model->relationship
插入相关模型
attach()
associate()
查询范围
使用数据透视表如果需要从数据透视表中检索其他数据。



