Create complex hasManyThrough Laravel 4 query - php

I have classes User, User_Role and Role_Permission with correspondent tables
users (id)
users_roles (user_id, role_id, one user_id has one role_id)
roles_permissions (role_id, permission_id, one role_id has many permission_id)
I want to get permissions for user via $user->permissions. For this I wrote function
public function permissions()
{
return $this->hasManyThrough('User_Role', 'Role_Permission', 'user_id','role_id');
}
I get the error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles_permissions.user_id' in 'field list' (SQL: select `users_roles`.*, `roles_permissions`.`user_id` from `users_roles` inner join `roles_permissions` on `roles_permissions`.`id` = `users_roles`.`role_id` where `roles_permissions`.`user_id` = 1)
What am I doing wrong? Thanks!

Switch the order of the first two arguments:
public function permissions()
{
return $this->hasManyThrough('Role_Permission', 'User_Role', 'user_id', 'role_id');
}
Eloquent is looking for the user_id column in the Role_Permission table, which it won't find..

Related

How to make a relation in laravel with multiple pivot tables?

I got a tables:
users (id, name, surname)
weddings (id, ...)
wedding_user (id, wedding_id, user_id, role_id)
wedding_user_permission (wedding_user_id, permission_id)
And I want to make a relation between Wedding and WeddingUser model (Wedding has many WeddingUser, WeddingUser belongs to Wedding).
Actually, if I'll ignore laravel relations, model will be:
//Wedding Model
public function users()
{
$users = WeddingUser::where('wedding_id', $this->id)->get();
return $users;
}
But I need to do this with the laravel relations.
I tried this:
public function users()
{
return $this->belongsToMany(
'App\Models\WeddingUser',
'wedding_user',
'user_id'
);
}
But it throws an error:
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'wedding_user' (SQL: select `wedding_user`.*, `wedding_user`.`user_id` as `pivot_user_id`, `wedding_user`.`wedding_user_id` as `pivot_wedding_user_id` from `wedding_user` inner join `wedding_user` on `wedding_user`.`id` = `wedding_user`.`wedding_user_id` where `wedding_user`.`user_id` in (1))
How to do it correctly?

Getting data from laravel relation on Foreign Key

I have to SQL tables: users and roles; The user table consists of an id (PRIMARY), email, password and a role_id (INDEX) column. The role table consists of an id (PRIMARY) and a name column. A user can only have a single role (Admin or User).
This is how my laravel Models look like:
// User Model
public function role()
{
return $this->hasOne(Role::class);
}
// Role model
public function user()
{
return $this->belongsTo(User::class);
}
What i want is, when i get the information of a user, i want to get the corresponding role of that user.
When i place this code in the Artisan Tinker:
// Get user with id=2
App\User::find(2)->role;
This seems logical to me "Find the role belonging to the user with id 2"
But it is throwing this error:
Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.user_id' in 'where clause' (SQL: select * from `roles` where `roles`.`user_id` = 2 and `roles`.`user_id` is not null limit 1)'
How Can i get the role of a User without calling it from the Role model?
Since you have a role_id on users table, you should have belongsTo(Role::class) on User model:
// User Model
public function role()
{
return $this->belongsTo(Role::class);
}
And hasMany(User::class) on role model:
// Role model
public function users()
{
return $this->hasMany(User::class);
}
I believe there should be belongsToMany instead of belongsTo. This should fix the problem. Documentation: https://laravel.com/docs/5.6/eloquent-relationships
Unknown column 'roles.user_id'
This is the error. Your roles table should have user_id column.

Laravel 5.3 hasManyThrough through an intermediate table

I have the following table relationship:
organizations
id - integer
organization_users
organization_id - integer (FK)
user_id - integer (FK)
users
id - integer
I am trying to get all the users of an organization through eloquent relationships. Here is my Organization.php model with its relationships:
class Organization extends Model
{
public function Users(){
return $this->hasManyThrough('App\User', 'App\OrganizationUser',
'organization_id', 'user_id', 'id');
...
}
I have tried many combinations of that relationship such as
return $this->hasManyThrough('App\User', 'App\OrganizationUser',
'user_id', 'organization_id', 'id');
But all turn up somewhat the same error (this one is from the first query):
Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not
found: 1054 Unknown column 'organization_users.id' in 'on clause' (SQL: select
`users`.*, `organization_users`.`organization_id` from `users` inner join
`organization_users` on `organization_users`.`id` = `users`.`user_id` where
`organization_users`.`organization_id` = 1)'
Is it possible that I can have the relationship retrieve the user_id to query on the users table instead of Laravel trying to retrieve organization_users.id? If not is there another way around this?
This is many to many relationship.
User Model:
public function organizations()
{
return $this->belongsToMany('App\Organization','organization_users');
}
Organization Model:
public function users()
{
return $this->belongsToMany('App\User','organization_users');
}
To, get all the users with their organizations:
$users=User::with('organizations')->get();
foreach($users as $user)
{
print_r($user->name);
foreach($user->organizations as $organization)
{
print_r($organization->name);
}
}
What you are describing looks like it may be a 'Many-to-Many' relationship.
https://laravel.com/docs/5.3/eloquent-relationships#many-to-many

Laravel 5 - Find Fields on "MorphOne" Relationship

I'm quite new to Laravel and I'm now facing this issue while trying to create a query:
I have the following Morphable classes:
\App\User
class User {
public function userable()
{
return $this->morphTo();
}
}
\App\Distributor
class Distributor {
public function user()
{
return $this->morphOne('App\User', 'userable');
}
}
user table has the fields: name, email, status, userable_type and userable_id.
distributor table has the fields: store_code and location_id.
By using Eloquent, i need to start the query from Distributor model and select only the following fields: 'name, email, store_code'.
I'm trying the following, but laravel says user.name doesn't exists :(
$queryBuilder = \App\Distributor::has('user');
$queryBuilder->select(['user.name']);
$queryBuilder->get();
QueryException in Connection.php line 651:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user.name' in 'field list' (SQL: select user.name from distributor where (select count(*) from user where user.userable_id = distributor.id and user.userable_type = App\Distributor and user.deleted_at is null) >= 1)
I was able to achieve my goal forcing the join relationship, but this seems wrong, I think Eloquent is able to find the relation by itself as the Morph relationship is specified in the Model.
Just for record, this works good:
$queryBuilder = \App\Distributor::has('user');
$queryBuilder->join('user', function($join) {
$join->on('userable_id', '=', 'distributor.id')
->where('userable_type', '=', \App\Distributor::class);
});
$queryBuilder->select(['user.name']);
$queryBuilder->get();
Also, since its a one-to-one like relationship, sometimes I'll need to order the results using one of the users columns
But I need another way to do it without forcing the join, something clean as the first example.
read about with() function in the docs
$queryBuilder->select('id','store_code');
$queryBuilder = \App\Distributor::with(['user'=>function($query){
$query->select('id','name','email')
}]);
$queryBuilder->has('user');
$queryBuilder->get();

Has many through with pivot table

A Venue hasMany Subscription
A Subscription belongsToMany User
How can I retrieve all User from Venue through Subscription?
I imagine something like:
$venue->subscribers // Return all `User`
My database scheme: http://www.laravelsd.com/share/AAjuYS
I have tried
class Venue {
public function subscribers() {
return $this->hasManyThrough('App\User', 'App\Subscription');
}
}
Fails with error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.subscription_id' in 'on clause' (SQL: select `users`.*, `subscriptions`.`venue_id` from `users` inner join `subscriptions` on `subscriptions`.`id` = `users`.`subscription_id` where `users`.`deleted_at` is null and `subscriptions`.`venue_id` = 1)
// In Venue class
public function subscribers()
{
return $this->hasManyThrough('App\User', 'App\Subscription');
}
You can read about it in the documentation, it's pretty straight-forward: http://laravel.com/docs/5.1/eloquent-relationships#Has-Many-Through

Categories