Laravel Has Many through relationship not working - php

I am new in laravel and I am facing issue with relationships.
I have three tables.
asset assetmaintenance users
id id id
name asset_id name
inspector_id(users_id)
name
I want to access all users attached with asset through assetmaintenance, so I define relationship in asset model like:
public function users(){
return $this->hasManyThrough(TenantUser::class,AssetMaintenance::class,'asset_id','id');
}
But the query generated by eloquent is different from what I expected:
select * from `assets` where exists (select * from `users` inner join `assets_maintenance` on `assets_maintenance`.`id` = `users`.`id` where `assets`.`id` = `assets_maintenance`.`asset_id` and `username` like ?) and `isDeleted` = ? order by `id` desc
I want relation like assets_maintenance.inspector_id= users.id but it's comparing assets_maintenance.id = user.id.
Please suggest...

Try with the below code:
public function users(){
return $this->hasManyThrough(TenantUser::class, AssetMaintenance::class, 'inspector_id', 'id');
}
And also try with additional parameters
For More
Laravel Has-Many-Through Relationship

Okay try this way
first, create a method in asset model for hasMany assetmaintenance and then after create another method in model for hasOne inspector_id and to fetch all those data in one query use below code.
Assets::with('assetmaintenance','assetmaintenance.user')->get()

Related

Handling relationship in model in laravel

I am learning relationships in Laravel php framework and I am trying to build this query
SELECT * FROM users u INNER JOIN link_to_stores lts ON u.id=lts.user_id INNER JOIN stores s ON lts.store_id=s.store_id WHERE lts.privilege = 'Owner'
I built this in Model
Link_to_store.php
public function store()
{
return $this->belongsTo('App\Store');
}
public function user()
{
return $this->belongsTo('App\User');
}
User.php
public function store_links()
{
return $this->hasMany('App\Link_to_store');
}
Store.php
public function user_links()
{
return $this->hasMany('App\Link_to_store');
}
I tried this query but this only joins user and link_to_store table
$personal_stores = Auth::user()->store_links->where('privilege','=','Owner');
Now I am confused how to join store table too. Can anyone help with this?
Schema is like this
Stores Table
store_id store_name
Users Table
id name
Link_to_stores Table
id store_id user_id privilege
I suppose store_links is actually a pivot table. In this case, you can use belongsToMany(), this will automatically take care of the pivot table.
To do this, in your User model you change the store function to this:
function stores() {
return $this->belongsToMany('App\Store', 'store_links', 'user_id', 'store_id')->withPivot('privilege');
}
Because the primary key of stores is not id, you will have to define this in you Store model with the following line:
protected $primaryKey = 'store_id';
Now to get the stores for a user, you simply call
$stores = Auth::user->stores()->wherePivot('privilege', 'Owner')->get();
I am learning relationships in Laravel php framework and I am trying to build this query
SELECT * FROM users u INNER JOIN link_to_stores lts ON u.id=lts.user_id INNER JOIN stores s ON lts.store_id=s.store_id WHERE lts.privilege = 'Owner'
You are trying to do a join here. You can do a join like this:
$stores = User::join('link_to_stores as lts', 'users.id', '=', 'lts.user_id')->join('stores as s', 'lts.store_id', '=', 's.id')->where('lts.privilege', 'Owner')->get();
But like Jerodev pointed out, it seems like Many to Many relationship might make more sense in your case. The difference is that relationship will actually execute 2 queries (1 for original model, 1 for relationship). It will then attach the related models to the original model (which is extremely handy).

Laravel 5 - 3 table relation fetch all data

I have 3 tables:
User-
id
name
Project
id
projectName
project-user
id
userId
ProjectId
I want fetch all data somethinglike that:
NEWTABLE
ProjectName
UserName
Right now my code looks like :
class Project extends Model
{
public function user(){
return $this->belongsToMany('App\User','Students','UserId','ProjeId');
}
}
So my question is, how can i fetch my data and manage data in the controller side using Eloquent?
thx for any help
If you want a "new table" with your names you could just use pure old SQL. In Laravel you use the DB class.
$mydataset = DB::select("SELECT U.name as UserName, P.name as ProjektName FROM User AS U, Project AS P, Project-User AS PU WHERE PU.userId = U.id AND PU.ProjectId = P.id")
You can do that through relations on both models, and then you query them using with like the example below:
Project Model
public function user(){
return $this->belongsToMany('App\User','project-user','user_id','project_id');
}
User Model
public function project(){
return $this->hasMany('App\Projects','project-user','user_id','project_id');
}
And then you can call them like this:
$user= User::find($user_id);
$user->project()->get()

Retrieve distant relation through has-many-through for many-to-many relation in Laravel

I have the following models in my application
User
Group
Task
which have the following relationships
User and Group have a many-to-many relationship
Task and Group have a many-to-many relationship
So basically a user can belong to more than one group and each group can have more than one task.
Following is the table structure.
users
id
name
groups
id
name
tasks
id
name
group_user
id
group_id (foreign key with groups table)
user_id (foreign key with users table)
group_tasks
id
group_id (foreign key with groups table)
task_id (foreign key with tasks table)
Now I want to retrieve all the tasks for the user.
I tried the following approaches and both didn't work.
Approach 1
$user->groups() gives the list of groups for a user
$group->tasks() gives the list of tasks for a group
So I tried
$user->groups()->tasks() but it didn't work.
Approach 2
I tried Has Many Through by adding this to my User model
public function tasks()
{
return $this->hasManyThrough(Task::class, Group::class);
}
but even that didn't work. The following is the error that I am getting
QueryException in Connection.php line 713:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'groups.user_id' in 'field list' (SQL: select `tasks`.*, `groups`.`user_id` from `tasks` inner join `groups` on `groups`.`id` = `tasks`.`group_id` where `groups`.`user_id` = 1)
My guess is that this is happening because it is expecting one-to-many relationship, but I have a many-to-many relationship.
So is there a way to retrieve it without getting all groups and then looping through them?
User Model
public function groups()
{
return $this->belongsToMany('App\Group');
}
Group Model
public function tasks()
{
return $this->belongsToMany('App\Task');
}
Task Model
public function groups()
{
return $this->belongsToMany('App\Group');
}
Retrieving all tasks for a user.
$user = User::find(1);
$user->load('groups.tasks');
$tasks = $user->groups->pluck('tasks')->collapse();
You can also take a look at the extension of the HasManyThrough here: https://github.com/staudenmeir/eloquent-has-many-deep
It helps you to retrieve many sub-levels of your relationships.
In your case, it would be
User -> belongsToMany(Groups) -> blongsToMany (Tasks)
just add your method to the user model like:
public function tasks()
{
return $this->hasManyDeep(
'App\Task',['App\Group']
);
}

How to create join query for multiple models with separate conditions in laravel Eloquent ORM

I want to create join query for multiple models with separate (model) conditions.
I have create following query :
select * from studentinformation as s left join studentattandence a on s.id =
a.studentid where s.PersonalFirstName='Kathi' and s.PersonalLastName='irfan'
and s.Age='2' and s.gender ='Male' and s.StudentCourse='1' and
s.GuardianFirstName='test' and s.GuardianLastName = 'test' and a.date
BETWEEN '2015-02-01' AND '2015-02-07'
Table of studentinformation model name is "StudentAdmissionModel".
Table of studentattandence model name is "StudentAttandenceModel".
How can i do this laravel Eloquent ORM.
You would need to declare a relationship between the two in the StudentAdmissionModel, which would look something like this:
class StudentAdmissionModel extends Eloquent {
public function attendance()
{
// Assuming a one-to-one relationship
return $this->hasOne('StudentAttandenceModel','studentid');
}
}
Then you would be able to use the whereHas() function to query the relationship:
$admissions = StudentAdmissionModel::where('PersonalFirstName','=','Kathi')
->where('PersonalLastName','=','irfan')
->where('Age','=','2')
->where('gender','=','Male')
->where('StudentCourse','=','1')
->where('GuardianFirstName','=','test')
->where('GuardianLastName ','=','test')
->whereHas('attendance',function($q)
{
$q->whereBetween('date', array('2015-02-01','2015-02-07'));
})
->with('attendance') // Optional eager loading, but recommended
->get();
And you would be able to access the fields like this:
foreach( $admissions as $admission){
echo $admission->gender;
// or
echo $admission->attendance->date;
}

How to use IN or Nesting of queires in Eloquent ORM of Laravel 4

I am converting my existing twitter clone toy project into Laravel 4. I have used codeigniter framework before and Eloquent ORM is the first ORM I have ever touched.
So I have confusion about how to do some advance queries,
Following query Is to fetch all the posts which are created by users who are being followed by current_user. This Stored procedure snippet works fine.
BEGIN
SELECT
tbl_users.id as user_id,
tbl_users.display_name,
tbl_users.username,
tbl_posts.id as post_id,
tbl_posts.post_text,
tbl_posts.`timestamp`
FROM tbl_posts , tbl_users
WHERE tbl_posts.user_id IN (
SELECT tbl_followers.destination_user_id FROM tbl_followers
WHERE tbl_followers.source_user_id = xSource_user_id
)
AND tbl_posts.user_id = tbl_users.id
ORDER BY tbl_posts.id DESC
LIMIT xLimit;
END
Table structure is like below :
users : (id)
posts : (id,src_user_id [FK], post_text )
followers : (id , dest_user_id [FK] , src_user_id [FK])
My best Guess is :
Post::where('user_id', 'IN' , Follower::where('from_user_id','=','1'))->toSql();
I have added following relationships to User model
public function posts()
{
return $this->hasMany('Post');
}
public function followers()
{
return $this->hasMany('Follower');
}
you need to use lists() to get results as array
Post::whereIn('user_id', Follower::where('from_user_id','=','1')->lists('id'))->toSql();
You can use IN in this way:
Post::whereIn('user_id', yourArray)->get();
But I suggest you to take a look at eloquent manual here, especially the relationships part

Categories