One to Many relation in laravel - php

I have 3 tables users companies company_users when I try to get user company details it return null
Logic
company has many users
user belong to 1 company
user model
public function company()
{
return $this->belongsTo(Company::class, 'company_users', 'user_id', 'company_id');
}
company model
public function user()
{
return $this->belongsToMany(User::class, 'company_users', 'company_id', 'user_id');
}
any idea?

it's not one to many relation it's many to many, with pivot table (company_users )
so, the relation should be like:
public function company()
{
return $this->belongsToMany(Company::class, 'company_users', 'user_id', 'company_id');
}
I recommend rename it to 'companies' cause it plural

Regarding to this comment:
If you really want one to many relation. Try this:
public function company()
{
return $this->hasMany(User::class);
}
public function user()
{
return $this->belongsTo(Company::class);
}

Related

Laravel Relationship not cascading to hasMany

I have 2 models, 'Tickets' and 'Messages', user can have many tickets and each ticket many messages.
class Message extends Model {
public function Ticket() {
return $this->belongsTo(Ticket::class, 'ticket_id', 'ticket_id');
}
public function user() {
return $this->belongsTo(User::class, 'user_id', 'user_id');
}
}
class Ticket extends Model {
public function messages() {
return $this->hasMany(Message::class, 'ticket_id', 'ticket_id');
}
public function user() {
return $this->belongsTo(User::class, 'user_id', 'user_id');
}
}
When trying to create a message attached to current user via the below code:
$Ticket->messages()->create([
'message' => $post['message']
]);
I get the following error:
Cannot insert the value NULL into column 'user_id', table 'messages'
Since Ticket is already linked to a user, I assumed it's going to cascade to message as well. I can manually specify it but I want everything to be built using laravel relationships the most correct way

Relationship between laravel models does not work

I have 2 models: one for users and one for clients. A user is a customer
User has a 'codigocli' field and client has a 'codigo' field
The relationships between my models are like this:
//User model
public function cliente()
{
return $this->hasOne(Cliente::class, 'codigo', 'codigocli');
}
//Cliente model
public function user()
{
return $this->belongsTo(User::class, 'codigocli', 'codigo');
}
My database is fine (I think) client has the 'codigo' field and users has the 'codigocli' field. So what am I doing wrong? When I want to query my home.blade.php with dd(auth()->user()-cliente()) I don't get anything, although it shows me the parent object fine.
H
You have an OneToOne relationship here so try this if you don't change id name:
//User model
public function cliente()
{
return $this->hasOne(Cliente::class, 'codigocli');
}
//Cliente model
public function user()
{
return $this->belongsTo(User::class, 'codigocli');
}
if you change id name:
//User model
public function cliente()
{
return $this->hasOne(Cliente::class, 'codigocli','local_id_name' );
}
//Cliente model
public function user()
{
return $this->belongsTo(User::class, 'codigocli', 'local_id_name');
}

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()

How can I make Laravel eloquent relationship with multiple tables?

I am trying to make 3 tables relationship like this,
users
id
name
roles
id
name
companies
id
name
company_role_user
user_id
role_id
company_id
Relationships in User.php model
public function companies() {
return $this->belongsToMany(Company::class, 'company_role_user', 'user_id', 'company_id');
}
public function roles() {
return $this->belongsToMany(Role::class, 'company_role_user', 'user_id', 'role_id');
}
public function role() {
// relationship to get role of specific company
}
Relationships in Company.php model
public function users() {
return $this->belongsToMany(User::class, 'company_role_user', 'company_id', 'user_id');
}
public function roles() {
return $this->belongsToMany(Role::class, 'company_role_user', 'company_id', 'role_id');
}
public function role() {
// relationship to get role of specific user
}
I want to get user role for specific company like this
User::find(1)->companies[0]->role->name
or
Company::find(1)->users[0]->role->name
If you have users
users
– id
– name
and you want them to have many to many relation with companies, you should do:
companies
– id
– name
user_companies
– user_id
– company_id
And for your roles, (many to many) you can do the same:
roles
- id
- name
user_roles
- user_id
- role_id
You are trying to make many to many 3 tables, when you should be doing it with 2 tables.
Even if you manage, it would be very complicated and confusing.
You should consider which tables should be related to roles, companies should have roles, or users should have roles, you dont need them both to have roles
Your schema looks correct but your model definitions/relations can use a junction/pivot model CompanyRoleUser which will relate these 3 relations as many-to-one/belongsTo and one-to-many/hasMany from Company/Role/User.
class Company extends Model
{
public function companyRoleUser()
{
return $this->hasMany(CompanyRoleUser::class, 'id', 'company_id');
}
}
class Role extends Model
{
public function companyRoleUser()
{
return $this->hasMany(CompanyRoleUser::class, 'id', 'role_id');
}
}
class User extends Model
{
public function companyRoleUser()
{
return $this->hasMany(CompanyRoleUser::class, 'id', 'user_id');
}
}
class CompanyRoleUser extends Model
{
public function company()
{
return $this->belongsTo(Discipline::class, 'id', 'company_id');
}
public function role()
{
return $this->belongsTo(Speciality::class, 'id', 'role_id');
}
public function user()
{
return $this->belongsTo(User::class ,'id','user_id');
}
}
Now you can apply different type of filters for your data like
Fetch users for company A id = 1 with admin role id = 2
User::whereHas('companyRoleUser.company', function ($query) use ($company_id) {
$query->where('id', $company_id);
})->whereHas('companyRoleUser.role', function ($query) use ($role_id) {
$query->where('id', $role_id);
});
Or
User::whereHas('companyRoleUser', function ($query) use ($company_id) {
$query->where('company_id', $company_id)
->where('role_id', $role_id);
});
Fetch companies with $user_id and $role_id
Company::whereHas('companyRoleUser', function ($query) use ($user_id) {
$query->where('user_id', $user_id)
->where('role_id', $role_id);
});

Laravel 5 Querying with relations causes "Call to a member function addEagerConstraints() on null" error

I have been trying to create a simple user management system but keep on hitting road blocks when it comes to querying relations. For example I have users and roles and whenever I try to make a query for all users and their roles I get an error. The one in the title is only the latest one I've encountered.
My User and Role Models look like this:
class Role extends Model
{
public function users()
{
$this->belongsToMany('\App\User', 'fk_role_user', 'role_id', 'user_id');
}
}
class User extends Model
{
public function roles()
{
$this->belongsToMany('\App\Role', 'fk_user_role', 'user_id', 'role_id');
}
}
My migration table for many-to-many relationship between the two looks like this:
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable(); //fk => users
$table->integer('role_id')->unsigned()->nullable(); //fk => roles
$table->foreign('fk_user_role')->references('id')->on('users')->onDelete('cascade');
$table->foreign('fk_role_user')->references('id')->on('roles')->onDelete('cascade');
});
}
And then I try to get all records with their relation in a controller:
public function index()
{
$users = User::with('roles')->get();
return $users;
}
So I need another pair of eyes to tell me what is it I am missing here?
You are missing return statements in the methods that define relations. They need to return relation definition.
Replace
public function roles()
{
$this->belongsToMany('\App\Role', 'fk_user_role', 'user_id', 'role_id');
}
With
public function roles()
{
return $this->belongsToMany('\App\Role', 'role_user', 'user_id', 'role_id');
}
You forgot the return in your functions
Do:
return $this->belongsToMany('\App\User', 'fk_role_user', 'role_id', 'user_id');
return $this->belongsToMany('\App\Role', 'fk_user_role', 'user_id', 'role_id');
You need to use Return for your function's result. If you do not do that, Laravel does not know What should do with that function without any action.
Just use like this
return $this->hasOne(xxx, xx, xx);
Enjoy your coding !
Make sure you have written return in your model function relation.
return $this->hasMany('App\StaffShift','user_id','user_id');

Categories