如何在Laravel中定义雄辩关系

时间:2022-10-16 07:46:53

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 <= User.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. 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()?

我知道我可以查询电影模型,并获得min_age小于或等于用户年龄的所有电影。我的问题是如何通过使用hasMany()或belongsToMany()等函数在User模型中定义一个Eloquent关系来实现这一目标?

1 个解决方案

#1


1  

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.

我们假设你也有一个auth系统。

$user = Auth::user();

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

#1


1  

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.

我们假设你也有一个auth系统。

$user = Auth::user();

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