简体   繁体   English

如何在Laravel中定义雄辩的关系

[英]How to define Eloquent relationship in Laravel

I have two models - the User model and the Movie model for the following tables 我有两个模型-下表的用户模型和电影模型

The user table has the following columns 用户表具有以下列

  • id ID
  • age 年龄

The movie table has the following columns 电影表具有以下列

  • id ID
  • min_age MIN_AGE

How do I define a relationship on the User model such that for each user, I am able to get all the movies which follow the constraint: 如何在User模型上定义一个关系,以便对于每个用户,我都能获得所有遵循约束的电影:

Movie.min_age <= User.age Movie.min_age <=用户年龄

I know that I can just query the Movie model and get all movies having min_age less than or equal to the age of the User. 我知道我可以查询Movie模型并获取所有min_age小于或等于用户年龄的电影。 My question is that how can this be achieved by defining an Eloquent relationship inside the User model using the functions like hasMany() or belongsToMany() ? 我的问题是,如何通过使用hasMany()belongsToMany()之类的函数在User模型内部定义一个雄辩的关系来实现?

So a user can watch many movies. 因此用户可以观看许多电影。 At the same time a movie can be watched from many users at the same time. 同时可以从许多用户处观看电影。

On User.php 在User.php上

public function movies(){

   return $this->hasMany(Movie::class);
 }

On Movie.php 在Movie.php上

public function users(){
  return $this->belongsToMany(User::class);
}

To get what you are looking for through relationship you do something like this; 为了通过关系获得您想要的东西,您可以执行以下操作:

Let us say that you have a auth system set as well. 假设您还设置了一个身份验证系统。

$user = Auth::user();

$getMovies = $user->movies()->where('min_age','<=',$user->age)->get();

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

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