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()
Related
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()
I have a website build in Laravel.
I have two tables - Groups and Group members.
For each group_member, the row in the table has id, group_id and user_id.
The groups have a name and a description.
When a user joins a group, a row is created in the group_member table.
But I now need to get the groups that a user is part of.
So if I have user_id = 5, I need to get all the rows in group_member where user_id = 5, and then get the corresponding group, so I can query the groups.
I need to do something like $groups = Groups::whereGroup_member ...
But I cant query the model like that, because in Groups there is no where it specificies who the members are, it is just the group details - the members are specificed in group_member table.
How do I get the groups, which a member is part of using the laravel query standards?
In your User.php Model
public function group_member(){
return $this->hasMany(GroupMember::class,'user_id','id;);
}
In your GroupMember.php Model
public function group(){
return $this->belongsTo(Group::class,'group_id','id');
}
Your query will be
$users = User::with('group_member.group')->find($user_id);
You should use Many-to-Many relation:
class Group
...
public function members() {
return $this->belongsToMany(User::class); // Users (members) that belongs to Group
}
class User
...
public function groups() {
return $this->belongsToMany(Group::class, 'group_member', 'user_id', 'group_id'); // Groups that User belongs to
}
And at controller, when You have user id:
$groups = User::where('id', $user_id)->groups;
More about this written at official docs: https://laravel.com/docs/5.4/eloquent-relationships#many-to-many
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).
I have two tables 1)users
{ id, password }
2)expertise { id, expertise}
the relationship I have is
Models
Expertise.php
function User()
{
$this->hasOne('Expertise');
}
User.php
function Expertise()
{
$this->hasOne('User');
}
So how can I query using Eloquent to get the first 10 users with a certain expertise?
I want to join users.id = expertise.id and get the first 10 people with a specified expertise (Where clause).
Beginner to laravel, I've checked other sources but was not successful
Right now you are having a problem with the way that you modeled your data. If you have a one-to-one relationship the best practice to model it is to have one entity store the id of the other. The Laravel convention for this is to have a column named <model>_id:
Users
| id | password |
Expertises
| id | expertise | user_id |
Then in your models you can do this:
Models
Expertise.php
class Expertise extends Eloquent
{
public function User()
{
// because expertise has a column user_id
// expertise belongs to user
return $this->belongsTo('User');
}
}
User.php
class User extends Eloquent
{
public function Expertise()
{
// because expertise is the one with the column
// user_id, user has one expertise
return $this->hasOne('Expertise');
}
}
The Query
After you have all this set up, to be able to query the first 10 users with a certain expertise you can do this.
$users = User::whereHas('Expertise', function($q)
{
$q->where('expertise', '=', <expertise you are looking for>)
})
->take(10)
->get();
To get a further reading in querying relationships in Laravel please take a look at this:
Laravel - Querying Relationships
Keep in mind
keep in mind that the tables name must be plural, if not then you should specify the name of the table inside the model:
protected $table = 'expertise';
I have a user's table for my application. I also have a pivot table for people who add other people to the application. I am trying to list out all the users that have been added by a user (1). How can I write this in eloquent?
Select u.* FROM users u join friend_user f ON u.user_id = f.friend_id where f.user_id = 1
I have it in a Friend model that presents the pivot table. Is it better to have a full query there or to create a friend function in the User and Friend class to show relationships?
<in User model> public function Friend(){ return $this->belongsTo('User'); }
If I understood you correctly, you should have the following in your User model:
public function friends()
{
return $this->belongsToMany('User', 'user_has_friends', 'user_id', 'friend_id');
}
Of course modify accordingly to your needs.
Now you can grab friends like this:
$user = User::find(1);
foreach($user->friends as $friend)
{
echo $friend->name .'<br>';
}