Yii - sorting by another table - php

I'm using Yii framework and have trouble with a query as i'm new to it.
I have two tables in my database:
users:
id, username, password, fullname
friends
id, user_id, friend_id
I declared the relationships and get the user's friends by using:
$userFriends = $user->userfriend();
My problem is that I want to get the list of friends ordered by the "fullname" column in the users table.
How can I achieve that?
Thank you

When declaring your relation, you can specify additional options http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-options
public function relations()
{
return array(
'friends'=>array(self::MANY_MANY, 'User', 'friends(user_id,friend_id)',
'order'=>'fullname ASC')
);
}

Related

Select two types information from same table in single query MYSQL

I have a 'users' table like bellow. When a new user sign in, he has to use one 'sponsor_id' from previous user. Previous user's 'user_name' being used as 'sponsor_id' for a new user. Now, I want to show some 'sponsor_id' details when a new user signed in like, sponsor_id's first_name, last_name, phone etc. All data are saved in 'users' table. What should be the query,Please anyone help me. I am using Laravel5.4.
I am trying something like-
$sponsor_info = DB::table('users')
->select('first_name','last_name','phone')
->where('user_name', '=', '$sponsor_id')
->first();
I dont know laravel but Im giving the solution plz convert it to laravel.
select m.*,
s.first_name,
s.last_name,
s.phone
from user m
left join user s
on m.sponsorid=s.userid
SELECT
user.id,
user.user_name,
user.sponsor_id,
sponsoredUser.user_name
FROM user
INNER JOIN user AS sponsoredUser ON user.sponsor_id = sponsoredUser.id
WHERE user.id = $id
Here I am using user table 2 times . First is using for that user and the second is using for the getting information of that sponsored user. That's why I given the second user table name an alias name called sponsoredUser .
Hope you will transfer this query into laravel.
Add this function to your user model:
public function sponsor()
{
$this->belongsTo(App\User::class,'sponsor_id','user_name');
}
Now you can make this query:
$users = App\User::with('sponsor')->get();
All users will have a "sponsor" relation loaded.
Foreach ($users as $user){
$user->sponsor->first_name;
// Etc
}

Laravel 5 - how to perform left join on same table

In my application, there's two tables at the moment: users and employees. The latter is simply a profile table for the boilerplate users table that ships with Laravel.
I have two foreign keys inside of employees, one is user_id that points to id on users table. So basically, the profile data of the registered user. The second foreign key in employees is manager_id. That is the id of the person who is the manager of an employee. Some users are managers and have a blank manager_id field.
I want to retrieve the row from my Employee model where the user_id matches the manager_idand then send them all to my view, where they will see the first_name and last_name of the manager. At the moment I see the manager ID instead of their name.
Sample LeftJoin =>
DB::connection('testing')->table('table1 as t1')
->select('t1.column, t2.column')
->leftJoin('table2 as t2','t2.client_id','=','t1.id')
->get();
Try some thing like this:
$users = DB::table('users t1')
->join('users t2', 't1.id', '=', 't2.user_id')
->select('your column list')
->get();
// here we are creating 2 aliases for users table which make it self join
In your Employees model add the following method:
public function manager()
{
return $this->hasOne('App\User', 'id', 'manager_id');
}
You can then get the name of the Manager like this:
$employee = \App\Employee::find(1);
$manager = $employee->manager()->first();
$manager_name = $manager->name;

How to get pivot data specific to user in Laravel?

I have a users table, an items table and a pivot table item_user.
I can get a list of all users items or a list of all an items users easy enough using belongsToMany relationship.
$item->users;
$user->items;
However I'm using this as a sort of "favorites" relationship.
So if I display ALL items on my website regardless of user, I want to know which ones the user has in the pivot table as the "favorite".
So far I have this:
// Item Model
public function favorites()
{
return $this->belongsToMany('App\Models\User')->withPivot('user_id')->where('user_id', #\Auth::user()->id);
}
It works fine, but the query it runs is this:
select `users`.*, `item_user`.`item_id` as `pivot_item_id`, `item_user`.`user_id` as `pivot_user_id` from `users` inner join `item_user` on `users`.`id` = `item_user`.`user_id` where `user_id` = '1' and `item_user`.`item_id` in ('282', '10', '826', '632', '896', '604', '8', '990', '175', '979', '7', '805', '665', '263', '507', '327', '397', '208', '762', '926', '474', '389', '433', '742', '613', '689', '782', '435', '898', '518')
I don't need the data from the users table, I just need the pivot data:
SELECT user_id, item_id FROM item_user WHERE user_id = 1 AND item_id IN (1, 2, 3, 4, 5, 6, 282);
Is there anyway to run the more efficient version in Laravel?
As much I understand your requirement.. it can be resolve by adding a column to pivot table.
First include 'favorite' on your pivot call to Item Model:
return $this->belongsToMany('User', 'user_items')
->withPivot('favorite');
Note: Vice versa can also define but didn't test that option.
Then to check weather it 'favorite' or not :
$item = User::with('items')->get()->find(1)->items->find(2)->pivot->favorite;
But in that case you also need to organise you relationship structure as user has many items. If you still any question to understand my approach please let me know.

Adding a HABTM as a registration in CakePHP

I have Users and Courses.
I have a users table, and a courses table.
I also have a course_memberships table with id |
course_id | user_id
I have the appropriate hasmany relationship
for courses and users to relate to CourseMembership
But I have no idea how to create that relationship using a button on the front end. Something like a public function register() on the Courses controller that would put the Auth User ID in the user_id field, and the course id in the course_id field to form the relationship.
I know it was a wall of text, but I figured a description of the issue may be more helpful than an endless scroll of code.
Can anyone help?
You should create a method to save to the CourseMembership model within the Courses Controller. Something like this would work.
public function register($course_id){
$user_id = $this->Auth->user('id');
$data = array(
course_id => $course_id,
user_id => $user_id;
);
if($this->Courses->CourseMembership->save($data)){
$this->Session->setFlash('Registered');
$this->redirect($this->referer());
}
else{
$this->Session->setFlash('Could not register');
$this->redirect($this->referer());
}
}
This way, when people go to /Courses/register/1, it would register them for the course with the ID of 1.
Then when you do a find on the User, the data would be in $user['CourseMembership']

Using relational AR to retrieve "OR" condition

I'm using the Yii framework and have come across an issue whilst building a Friend/Connection style system. I have a standard users table and to store friends I have a friends table with the following layout (the appropriate FKs etc have been set up):
id | userId | friendId | and some other fields...
As the "friend" is mutual - so, if user A is a friend with user B, then user B is a friend with user A - therefore there is only ever one entry per "friendship".
What I'm trying to do is use Yii's relational query to eventually return items which belong to friends. Currently I have the following relation in the User model...
'friends' => array(self::HAS_MANY, 'UserFriend', 'userId'),
However that only returns 'friends' if the user's ID is present in the userId field. If the user's ID is in the friendId field then the "friendship" won't be recognised.
Is there a way to query using "OR" - for example: if user's ID == userId OR user's ID == friendId then return that entry?
In addition, is there a way to get Yii to return the other ID, so if user's ID == userId it will return friendId, else if user's ID == friendId it will return userId?
I'm eventually trying to do something like:
$userModel = User::model()->findByPk(Yii::app()->user->id); // user's model
$userFriends = $userModel->with(items)->friends; // return friends with their items
Hopefully I haven't confused too many! Sorry for the poor explanation
Thanks :)
Follow the instructions here on creating a database command object, and then you can query with an OR condition as follows:
$command->where(array('OR', 'userID = :userID', 'userID = :friendID'), array(':userID' => $userID, ':friendID' => $friendID));
Do you want get all friends of current user of your app?
You can use CDbCriteria and method find(). Something like this:
$criteria = new CDbCriteria;
$criteria->addCondition('id = :userid');
$criteria->addCondition('friendid = :userid', 'OR'); // OR - the operator to join different conditions. Defaults to 'AND'.
$criteria->params = array(':userid' => Yii::app()->user->id);
$userFriends = UserFriend::model()->find($criteria);
But I'm not sure in your User and UserFriend models structure and mutual relations. Have you some relation from UserFriend to User? If so, than you can use something like $userFriends->user0 after code above.
CDbCriteria details
find() method details

Categories