Yii2 query for users in group - mysql

I had a DB that had a user table and a group table and the group table had a column user_id which made it simply to return a list of users in a group:
$users = User::find()
->where(['{{user}}.group_id' => $group_id])
->all();
Now the user_id column is gone and there is a third table group_user with user_id and group_id columns for the relationship.
I tried this:
$users = User::find()
->innerJoinWith('group_user)
->where(['{{group_user}}.group_id' => $group_id])
but received this error:
User has no relation named "group_user"
But I set the relationship in the User model:
public function getGroupUser() {
return $this->hasOne(GroupUser::className(), ['user_id' => 'id']);
}
What am I missing? This is used in a Humhub API.

I would reprogram your getGroupUser (renaming it to getGroups) relation using viaTable:
public function getGroups() {
return $this->hasMany(Group::className(), ['user_group.id_group' => 'group.id'])
->viaTable('user_group', ['user.id' => 'user_group.id_user']);
}
That would give you the Group(s) a User belongs to. But I think you are aiming to get the Users that belong to a given group, so similarly I would create a getUsers relation in your Group model:
public function getUsers() {
return $this->hasMany(User::className(), ['id' => 'user_id'])
->viaTable('group_user', ['group_id' => 'id']);
}
Then:
$group = Group::findOne($id_group);
$users = $group->getUsers()->all();

Related

Laravel 8 insert data to multiple connected tables

I have two tables: (Table A & TableB).
Table A = id(primary), name, email
Table B = user_id(foreign(id)), column1, column2
What I need to do is:
Insert a row in Table A.
Verify the insertion.
Insert row in Table B & store Table A (id) in Table B (user_id).
Currently, I'm handling it like the following.
// Create a row in Table A
$createUser = UserModel::create($userData);
// Verifying insertion of the by checking if id is set
if (isset($createUser['id'])) {
$adminData = [
'name' => $info['adminName'],
'user_id' => $createUser['id'], // insert into user_id
'email_address' => $info['adminEmail'],
'contact_number' => $info['adminNumber'],
];
$createAdmin = AdminsModel::create($adminData);
}
I'm looking for a better way for multiple chained tables to avoid an if-else ladder.
There is nothing wrong with what you are doing. But you can also use eloquent relationships.
First define this method in the UserModel.
/**
* Get the admin associated with the user.
*/
public function admin()
{
return $this->hasOne(AdminsModel::class);
}
And use it like so
$createUser = UserModel::create($userData);
$createUser->admin->create([
'name' => $info['adminName'],
'email_address' => $info['adminEmail'],
'contact_number' => $info['adminNumber'],
]);

Compare two fields within different table using Laravel

I have two tables employees and customers , i've gave the schema below.
Customers('id' , 'username', 'location');
Employees('id' , 'EmployeeID' , 'CustomerID', 'location');
Currently I can use a query to retrieve customers details like the below query , note this is when the user is logged into the system hence the Auth::
$customerQuery1 = DB::table('customer')
->where('id', '!=', Auth::id())
->where('item', '=' , Auth::customer()->recommendation)
->get();
Each Employee has many customers ,I want other customers to see other customer items so i have attach the CustomerID field which is a foreign key and relates to the id field within the Customer table.
I've tried something like the below however I think I may need a join query but i'm unsure.
$query2 = DB::table('Customer','Employee')
->select('username')
->where(['EmployeeID' => Auth::id(), 'CustomerID' => 'id'])
->get();
$query2 = DB::table('Customer')
->select('username')
->join('Employee', 'Customer.id', '=', 'Employee.CustomerID')
->where(['EmployeeID' => Auth::id(), 'CustomerID' => 'id'])
->get();
I am then returning the values to my blade file like the below
return view ('pages.dashboard')
->with('query1',$query1)
and then Im using php indentation within my blade file to return the users data
#foreach ($query1 as $Userfound)
{{ $Userfound->username}}</p>
#endforeach
Actual Query needed in plain english
so I need to select a customer , where CustomerID == id
NOTE: id is from the customers table, CustomerID stored in the Employees table.
You can create Models using Laravel, for example:
Employee.php
public function customers()
{
return $this->hasMany('App\Customer');
}
Customer.php
public function employee()
{
return $this->belongsTo('App\Employee');
}
Which you can access like so:
$customer = Customer::where('id',Auth::user()->id)->firstOrFail();
or
$employee = Employee::where('id',Auth::user()->id)->firstOrFail();
And to see an employee's customers:
$employee->customers()->get();
Or to see the other customers of $customer's employer:
$customer->employee()->customers()->get();

Insert data into pivot table in Laravel5.4

I am working in Laravel5.4. I have created 3 table's.
User table :
tickets table :
ticket_cc_users table :
Now, I have create relation ship between users and tickets module like below.
User model :
public function tickets()
{
return $this->belongsToMany('App\User', 'ticket_cc_users', 'user_id', 'ticket_id');
}
Ticket model :
public function users()
{
return $this->belongsToMany('App\Models\Tickets\Ticket', 'ticket_cc_users', 'ticket_id', 'user_id');
}
TicketController controller save method :
public function store(Request $request)
{
return $request->all();
$ticket = new Ticket;
$ticket->requester_id = $this->user['id'];
//$ticket->assignee_id = $request->assignee_id;
//$ticket->cc_id = $request->cc_id;
$ticket->type = $request->type;
$ticket->priority = $request->priority;
$ticket->subject = $request->subject;
$ticket->description = $request->description;
$ticket->status = $request->status;
if($request->link)
{
$ticket->link = $request->link;
$ticket->due_date = null;
}
if($request->due_date && $request->due_date !="")
{
$ticket->due_date = date('Y-m-d',strtotime($request->due_date));
$ticket->link = "";
}
if($ticket->save())
{
$ticket->users()->sync($request->cc_id);
foreach($request->ticket_tags as $value){
$tag = new Tag;
$tag->tag_name = $value['text'];
$tag->save();
$ticketTag = new TicketTag;
$ticketTag->tickets_id = $ticket->id;
$ticketTag->tags_id = $tag->id;
$ticketTag->save();
}
$data = Ticket::find($ticket->id);
Mail::to('khyati#infirays.com')->send(new CreateTicket($data));
$response = array(
'success' => true
);
}
return $response;
}
Here, I am going to store data into ticket table. So I need to store cc user data into ticket_cc_user table. So how can I store ticket_id and user_id into this table. Here, I can get multiple user_id. And I am using Eloquent ORM.
Here, It gives an error like SQLSTATE[42S22]: Column not found: 1054 Unknown column '$$hashKey' in 'field list' (SQL: insert into ticket_cc_users ($$hashKey, address, city_id, country_id, created_at, deleted_at, email, firstname, id, introducer_id, is_verified, lastname, phone, signature, state_id, ticket_id, updated_at, user_id, username, userrole_id) values (object:109, , , , 2017-02-10 05:26:01, , nisarg.b#infirays.com, , 26, 1, , , 9999999999, , , 1, 2017-02-14 08:33:18, 0, nisarg, 2))
So,what code should I have to change in save function to store data into ticket_cc_users table?
It seems that belongsToMany() parameters order should be changed. The first and the last(4-th) parameters should be "about" same instance.
UPDATE Also the body of tickets() and users() functions should be exchanged
So try this:
User model :
public function tickets()
{
return $this->belongsToMany('App\Models\Tickets\Ticket', 'ticket_cc_users', 'user_id', 'ticket_id');
}
Ticket model :
public function users()
{
return $this->belongsToMany('App\User', 'ticket_cc_users', 'ticket_id', 'user_id');
}
From Laravel Many To Many Docs:
The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to:
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');

Relations viaTable yii2

I have 3 tables (order, order_delivery, order_types). Every table has model. For order I create GridView. Table order has column order_number, table order_delivery has order_number and order_delivery_code, table order_type has delivery_types_code and delivery_types_name. In Order I write function
public function getType() {
return $this->hasOne(OrderDelivery::className(), ['order_id' => 'order_id'])
->viaTable('delivery-types', ['delivery-types_code' => 'order_delivery_code']);
}
In index I write type.delivery-types_name - there is
Getting unknown property: backend\models\Order::order_delivery_code
What I do wrong?
Upd. my fault)
public function getType(){
return $this->hasOne(DeliveryTypes::className(), ['delivery-types_code' => 'order_delivery_code'])
->viaTable('order_delivery', ['order_id' => 'order_id']);
}

Yii2 order by 3rd table's value

I'm working with Yii2 and I can't solve it out. I need to OrderBy first table's rows by the third table's column.
First table: user [id, ....]
Second table: info [id, user_id, city_id, ...]
Third table: city [id, title, latitude, longitude]
models/User:
public function getInfo()
{
return $this->hasOne(InfoClear::className(), ['user_id' => 'id']);
}
models/Info
public function getCity()
{
return $this->hasOne(City::className(), ['id' => 'city_id']);
}
models/RecommendedSearch
$query = User::find()->joinWith(['info']);
Also I have to connect somehow 'city' table
Somthing like this
User::find()->joinWith(['info' => function(\yii\db\ActiveQuery $q){
$q->joinWith('city');
}]);
Or try
User::find()->with('info.city')->all();