Laravel get model by hasManyThrough - php

I have 3 classes - User, Business and BusinessRoleUser (and respective tables)
(user) id | first_name | last_name
(business) business_id | business_name
(business_role_user) user_id | business_id | role_id
I have combined the role of the user in the same table as their are multiple roles that user's can have towards a business i.e. admin, staff, etc. which are in the business_roles table.
I would like to access the Business Model through a logged in User to update fields i.e.
$business = User::find(Auth::id())->business();
$business->fill(Input::all());
$business->save();
At present in my User class I have the following (really each user will only be associated to one business):
public function business()
{
return $this->hasManyThrough('App\Business', 'App\BusinessRoleUser', 'business_id', 'user_id');
}
But If I do a simple dd(User::find(Auth::id())->business->business_name);
it throws an error
business name is undefined
It's not actually finding the business model associated to the user. I've looked at many examples of hasManyThrough but am failing to get this to work, appreciate the help!
(note user table uses id where as other tables use user_id, not sure if this is causing an issue)

Related

Laravel - how to display data of two tables using their pivot table

There are three tables:
-
users (id, name,email,password)
-roles(id, name)
-user_roles(user_id,role_id)
What I am trying to do
Get the user_id from user_roles and using a foreach loop, display which role_id are assigned from role to it e.g.
John Doe | Manager
Jane Doe | Admin
EDIT: In response to Andy Holmes comment below:
In User model, the following relationship exists, with an inverse in the Role model.
public function roles(){
return $this->belongsToMany('App\Role')->withTimestamps();
}
If I understand the scenario correctly, you should be able to access this directly from your Model's Relationship.
You can do the following to access the user's role information:
$user->roles and place this inside your loop

Laravel 5 and EAV relationship

I'm in trouble with eav model. Basically; i have three tables. User, UserInfo, Country.
User userinfo Country
--------- ------------ ------------
id id id
username user_id country_name
pass option_id
etc option_value
I connected user and userinfo models succesfully. There is a no problem.
I retrieving user infos in user model with this:
$this->info->where('option_id', $key)->first()->option_value;
My problem is right there. I'am storing "country_id" in option_id and option_value.
In example:
userinfo
--------
id 1
user_id 5
option_id country_id
option_value 3
I am running this query from user model
$this->info->where('option_id', 'country_id')->first()->option_value;
It returns 3. There is a no problem. My problem is i couldn't get country_name.
I don't know which relationship to use for this.
I can make this using "DB" class but then i need use another queries for all of theese types. It's not the best solution.
Can someone help me?
Edit : I am looking for like this solution (if it's possible):
$this->info->where('option_id', $key)->first()->option_value->country_name;
Edit : I am using laravel 5.1
The Country model belongs to the userinfo.
On your userinfo model, you should define the relationship.
UserInfo Class
public function country()
{
return $this->belongsTo('App\Country', 'local_key', 'parent_key');
}
In this case, your 'local_key' would be 'option_id' and your 'parent_key' would be 'id'.
Once you've defined the relationship, you can get all attribute of country like this:
$this->info->where('option_id', $key)->first()->country()->get();

Best way to detect if a user is a friend, has a friend request from, or has friend requested in Laravel Eloquent

I'm trying to create a user profile which has a few friend management buttons but you only want to see what is relevant to you and the profile.
I have two tables:
user_friendships - user_id | friend_user_id
user_friendship_requests - user_id | target_user_id
The relationship to get all friendships and friendship requests would be as follows:
class User extends Model
{
public function friends()
{
return $this->belongsToMany('User', 'user_friendships', 'user_id', 'friend_user_id');
}
public function friendrequests()
{
return $this->belongsToMany('User', 'user_friendship_requests', 'user_id', 'target_user_id');
}
}
This works fine but how would I detect if the user's profile I am visiting ($profile = User::find(1234)) is my friend OR they have friend requested me OR I have friend requested them?
It's the case of checking if rows exist between the two users, and seeing what column contains what. I'm not sure the best way to go about this because 3 queries, one for each state, probably isn't the best performance wise.
How would I go about this?
You can add a column called 'relation' that contains an enum.
$table->enum('relation', ['request', 'friend']);
However, you still need to worry about the opposite way. For example, a friendship would be defined as :
user_id | friend_user_id | relation
1 | 2 | friend
2 | 1 | friend
or with just with one unique row but you will need to include more checks into your SQL query. I'm wondering which of the two methods is the most suitable.
let's say your id is 50 and the profile id you are visiting is 1234
it is clear that
$profile = User::find(1234)->friends()->get()
will retrieve the user and all his friends
but what about filtering this friends
$users = User::with(['friends' => function ($query) {
$query->where('friend_user_id', '=', '50');
}])->first();
if($user)return "he is a friend";
the same in the request
to get out of the box soultions read eloquent-relationships eager-loading

Laravel: Complicated Eloquent Relationship - hasManyThrough or belongsToMany approach?

I have three Models (Organization, User, Visit) and 4 tables (organizations, users, organization_user, visits). I'm trying to get the accumulative total of user visits for an Organization.
Organization
------------
id,
name
User
---------
id,
name
Organization_User
----------------
id,
organization_id,
user_id
Visit
--------------
id,
user_id
views
Just to clarify, there is no Organization_User model, that is just the pivot table used by User and Organization:
$organization->belongsToMany('User');
$user->belongsToMany('Organization');
I could query all the user_ids from the pivot table by group_id, and then get all the visits for each user_id, but what's the more Eloquent approach?
A User hasMany Visits and a Visit belongsTo a User. A Visit doesn't belong to an Organization.
Solved it by using whereIn(). Basically with no change to my current relationship setup...to get accumulative views I did this:
$org = Organization::find($org_id);
return DB::table('visits')->whereIn('user_id', $org->users->modelKeys())->sum("views");
The modelKeys() returns all the user ids tied to that Organization. Then I get the sum of all the views for those users.
*Note it's also important to use Organization::find and not DB::table('organization') in order to maintain the Eloquent relationship. Otherwise $organization->users will give an error.
I think you might want a 'Has Many Through' relationship like so:
class Organization extends Model
{
public function visits()
{
return $this->hasManyThrough('App\Visit', 'App\User');
}
}
Then you could call count().
Laravel 5.1 doc

How to get courses through transactions table Laravel

I want to get all users with courses through transaction table.
Here is my db structure
course
id | name | description | price
transactions
id | course_id | user_id | name | description | expires
users
id | username | email
http://laravel.io/bin/da08n
I have tried with joins but it returns the same user multiple times.
DB::table('transactions')->join('users', 'transactions.user_id', '=', 'users.id')->join('courses', 'transactions.course_id', '=', 'courses.id')->distinct()->get();
How can I achieve this with Eloquent or in an other way?
Well.
you have a table called transactions, and a table of courses. Now, each transaction is related to a course.
Pay Attention: You have one record in one table which is related to another one record in another table, this is called one-to-one relationship.
In laravel, you achieve this by using Model's relationship.
You have one model called 'Transaction', and another model which is called 'Courses".
You get, for example one record from courses table by using Cources::find($myId).
Now, if you want to get a record of transactions by relating it to courses table., you should do this (in Laravel):
In your translation model define a method called course:
public function course ()
{
$this->hasOne("course"); // course is the name of another model which should be related
}
And then you use it like this:
$result = Transaction::find($myCourseId)->course();
Though for your case, you want to get many records through matching one record of a table to the another record of another table. Well:
In Transaction model add the following method:
public function Users()
{
return $this->hasManyThrough('User', 'Course');
}
With the above method you should be able to get the Users through Course method based on transactions.
More on that, please visit:
http://laravel.com/docs/eloquent#relationships

Categories