- Table Users => id, first_name, ...
- Table Tags => id, name
- Pivot Table user_tags => id, user_id, tag_id, ...
I'm using this in User Model:
public function tags()
{
return $this->belongsToMany('App\Tag', 'user_tag');
}
And this in TagsController:
$users = User::with(['tags'])->get();
What I need is to get only users that have tags with empty users tag
My Answer:
In Laravel Eloquent, you can define relationships between models using functions. Here is an example of how you can define a relationship between the Users table and another table:
php
// User model
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
// Post model
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
In this example, we have defined a one-to-many relationship between the User and Post models. The `posts()` function in the User model defines that a user can have many posts, while the `user()` function in the Post model defines that a post belongs to a user.
You can then use these relationships to retrieve related data like this:
php
$user = User::find(1);
$posts = $user->posts;
This will retrieve all the posts associated with the user with ID 1. Similarly, you can retrieve the user associated with a post like this:
php
$post = Post::find(1);
$user = $post->user;
Rate this post
4 of 5 based on 9413 votesComments