How to get records from 3 belongsToMany - php

I have a table structured like this.
user_company
user_id
company_id
user_dispensary
user_id
dispensary_id
user_group
user_id
group_id
// User.php
public function groups()
{
return $this->belongsToMany(Group::class,'user_group','user_id');
}
public function dispensary()
{
return $this->belongsToMany(Dispensary::class, 'user_dispensary', 'user_id');
}
public function company()
{
return $this->belongsToMany(Company::class, 'user_company', 'user_id');
}
// Company.php
public function dispensary()
{
return $this->hasMany(Dispensary::class);
}
public function users()
{
return $this->belongsToMany(User::class, 'user_company', 'company_id');
}
// Dispensary.php
public function company()
{
return $this->belongsTo(Company::class);
}
public function users()
{
return $this->belongsToMany(User::class, 'user_dispensary', 'dispensary_id');
}
I have tried this to get the users of the company where the user is.
\Auth::user()->company()->first()->users
But what I want is to get the records of all the users in a company where the current loggedin user is along with their groups and the users of the dispensaries where those dispensaries belongs to the company where the current user is.

Related

Check user if is in chat room Laravel

I have models:
ChatRoomMembers
ChatRoom
so I want to check if auth user is in chat room
my relationships:
ChatRoom:
public function chatRoomMembers()
{
return $this->hasMany(ChatRoomMember::class);
}
ChatRoomMembers:
public function chatRoom()
{
return $this->belongsTo(ChatRoom::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
So I created relationship in User Model:
public function chatRooms(){
return $this->hasManyThrough(
ChatRoom::class,
ChatRoomMember::class,
'user_id',
'id',
'id',
'chat_room_id'
)->orderBy('created_at', 'DESC');
}
and I am getting only this user chat rooms
In user model add below relationship
public function chatRoomMember(){
return $this->hasMany(ChatRoomMembers::class);
}
and in code
auth()->user()->chatRoomMember->count()
or
auth()->user()->chatRoomMember->exists()

User has many items with folders

I am trying to make an Eloquent query where I can get the Auths users expenses of a particual folder.
Example, get all Auth Users expenses that are linked to folder of id 2.
I have 3 tables,
expenses
-----------
id
folders
-----------
id
folder_expense
-----------
id
expense_id
folder_id
Currently I have these as my models.
User
---------------
public function expenses() {
return $this->hasMany('App\Expense', 'user_id', 'id');
}
public function folders() {
return $this->hasMany('App\Folder', 'user_id', 'id');
}
Expense
---------------
public function user() {
return $this->belongsTo('App/User', 'user_id');
}
public function folders() {
return $this->belongsToMany('App/Folder', 'folder_expense', 'folder_id', 'id');
}
Folder
---------------
public function user() {
return $this->belongsTo('App/User', 'user_id');
}
public function expenses() {
return $this->belongsToMany('App/Expense', 'folder_expense', 'expense_id', 'id');
}
I've made that pivot table thinking I could do something like this
Auth::user()->expenses()->folders()->where('folder_id', 2)->get()
How about?
Auth::user()->folders()->where('id', 2)->with(['expenses'])->get()

How to set relation in laravel with two ids?

I have these two tables:
product
- id
- name
favorites
- id
- product_id
- user_id
So, a user can add product to favorites only once. How can I set up this relation something like the following?
public function favorites() {
return $this->hasOne(Favorite::class, 'user_id', 'product_id')
}
So, I want to use both product_id & user_id such that the query would return proper result as per the following:
Get me the wishlist of user with id 1 and product with id 13!
you can do something like that:
in favourite Model class:
public function product(){
return $this->belongsTo('App\Product');
}
public function user(){
return $this->belongsTo('App\User');
}
In Product Model Class:
public function favorites(){
return $this->hasMany('App\Favorite');
}
In User Model Class:
public function favorites(){
return $this->hasMany('App\Favorite');
}
The user may have many favorites, so in Class User
public function favorites()
{
return $this->hasMany('App\Favorite');
}
Class Favorite
public function product()
{
return $this->belongsTo('App\Product');
}
public function user()
{
return $this->belongsTo('App\User');
}
If you have user you can
$userFavProducts = $user->favorites;
$product2 = $user->favorites()->where('product_id', 2)->get();
You should try this:
Favorites Model
public function product(){
return $this->belongsTo('App\Product','product_id');
}
public function user(){
return $this->belongsTo('App\User','user_id');
}

3 models many-to-many sync in Laravel 5.4

I have 3 models with the relations many-to-many:
Module
public function permissionTypes()
{
return $this->belongsToMany(PermissionType::class, 'permissions')->withPivot('role_id');
}
public function roles()
{
return $this->belongsToMany(Role::class, 'permissions')->withPivot('permission_type_id');
}
Role
public function permissionTypes()
{
return $this->belongsToMany(PermissionType::class, 'permissions')->withPivot('module_id');
}
public function modules()
{
return $this->belongsToMany(Module::class, 'permissions')->withPivot('permission_type_id');
}
PermissionType
public function roles()
{
return $this->belongsToMany(Role::class, 'permissions')->withPivot('module_id');
}
public function modules()
{
return $this->belongsToMany(Module::class, 'permissions')->withPivot('role_id');
}
tables description:
modules
id
title
status
roles
id
title
permission_types
id
title
pivot table permissions
id
role_id
module_id
permission_type_id
My synchronization looks like:
//array of ids from request to synchronization
$permissions = $request['permissions'];
//role by id from request
$role = Role::findOrFail((int)$roleId);
//module by id from request
$module = Module::findOrFail((int)$moduleId);
//synchronization
$pivotData = array_fill(0, count($permissions), ['role_id' => $role->id]);
$syncData = array_combine($permissions, $pivotData);
$module->permissionTypes()->sync($syncData);
When trying to make the synchronization, have an error
QueryException in Connection.php line 647:
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'permissions' (SQL: select permissions.*, permissions.role_id as pivot_role_id, permissions.permission_id as pivot_permission_id from permissions inner join permissions on permissions.id = permissions.permission_id where permissions.role_id = 1)
Thanks
IMHO you are trying to design a triple many to many that does not exists in Laravel. The solution, usually is to give the pivot table (in your case permissions) a Model (Permission in below code) for defining hasManyThrough relations.
If I understood well your table structure I will design the following relationships:
Module
public function permissions()
{
return $this->hasMany(Permission::class);
}
public function roles()
{
return $this->hasManyThrough(Role::class, Permission::class);
}
public function permissionTypes()
{
return $this->hasManyThrough(PermissionType::class, Permission::class);
}
Role
public function permissions()
{
return $this->hasMany(Permission::class);
}
public function permissionTypes()
{
return $this->hasManyThrough(PermissionType::class, Permission::class);
}
public function modules()
{
return $this->hasManyThrough(Module::class, Permission::class);
}
PermissionType
public function permissions()
{
return $this->hasMany(Permission::class);
}
public function modules()
{
return $this->hasManyThrough(Module::class, Permission::class);
}
public function roles()
{
return $this->hasManyThrough(Role::class, Permission::class);
}
Permission
public function permissionType()
{
return $this->belongsTo(PermissionType::class);
}
public function role()
{
return $this->belongsTo(Role::class);
}
public function module()
{
return $this->belongsTo(Module::class);
}
Tell me if it could work for you.

Laravel 5: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.moderators'

I'm guessing it's a Model relations error but I can't seem to pin it down.
I have 4 tables
users: id, name, email...
subreddits: id, user_id...
posts: id, title, subreddit_id, user_id...
moderators: id, user_id, subreddit_id...
I am trying to get all posts with eager loading 'user.votes' and 'subreddit.moderators'
$post = Post::with('user.votes')->with('subreddit.moderators')->findOrFail($post->id);
But I keep getting this error
QueryException in Connection.php line 636:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.moderators' in 'where clause' (SQL: select * from users where users.moderators in (17))
If I load it with subreddit alone, it will work, but I need to get the moderators of the subreddit as well.
EDIT: I removed moderators field from moderators() method in Subreddit Model and replace App\User with App\Moderator and I am now able to get the subreddit in question and its moderators. However, access $post->subreddit->moderators->user_id gives me this error Undefined property: Illuminate\Database\Eloquent\Collection::$user_id
These are my Models
User Model
public function subreddit() {
return $this->hasMany('App\Subreddit');
}
public function posts() {
return $this->hasMany('App\Post');
}
public function votes(){
return $this->hasManyThrough('App\Vote','App\Post');
}
public function moderators(){
return $this->hasManyThrough('App\Moderator', 'App\Subreddit');
}
Subreddit Model
public function user() {
return $this->belongsTo('App\User');
}
public function posts() {
return $this->hasMany('App\Post');
}
public function moderators() {
return $this->hasMany('App\User', 'moderators');
}
Post Model
public function user() {
return $this->belongsTo('App\User');
}
Moderator Model
public function subreddit() {
return $this->belongsTo('App\Subreddit');
}
public function user() {
return $this->belongsTo('App\User');
}
public function posts() {
return $this->belongsTo('App\Post');
}
public function subreddit() {
return $this->belongsTo('App\Subreddit');
}
public function votes() {
return $this->hasMany('App\Vote');
}
public function moderators() {
return $this->hasMany('App\Moderator');
}
Vote Model
public function user() {
return $this->belongsTo('App\User');
}
public function posts() {
return $this->belongsTo('App\Post');
}
Gate authorization in AuthServiceProvider
$gate->define('update-post', function ($user, $post, $isModerator) {
// Check if user is subreddit owner
if ($user->id === $post->subreddit->user->id) {
return true;
}
// Check if user is the post author
if ($user->id === $post->user_id) {
return true;
}
// Check if user is a moderator of a subreddit
if ($isModerator) {
return true;
}
return false;
});
If you want a collection of user IDs for all moderators, use this:
$ids = Post::findOrFail($id)->subreddit->moderators()->lists('user_id');
If you want to check if the given user is a moderator on the subreddit, use this:
$subreddit = Post::findOrFail($id)->subreddit;
$isModerator = $subreddit->moderators()->where('user_id', $user->id)->exists();

Categories