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']);
}
Related
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'],
]);
Table One:
ar_codes
----------
ar_id (primary key),
act_id,
ar_code,
status
Table Two:
act_req_recv
----------
rcv_id (primary key),
act_id,
rcv_person,
status
Now I need to find the ar_codefield value from ar_codes table for the rcv_person field of act_req_recv table. Both of the table has one common field which is act_id and is not a primary key for both of the table.
Now I can find it by normal mysql scriptlike bellow command, where $actId is carrying the value. How can I find this value in Yii?
SELECT ar_code FROM ar_codes WHERE act_id=$actId
I tried to find that with a function call from model. But as the field is not PK so the result is not coming.
public static function getAR_code($actId) {
$ActCode = Yii::app()->db->createCommand()
->select('ar_code')
->from('{{ar_codes}}')
->where('act_id=' . (int) $actId)
->queryAll();
return $ActCode;
}
Getting this error when the function run:
[error] [php] Array to string conversion
(D:\Xampp\htdocs\framework\yii1.1.19\zii\widgets\CDetailView.php:240)
The cDetail View Code is:
array(
'name' => 'actId',
'type'=> 'raw',
'value' => ActivityRecord::getAR_code($model->actId),
'htmlOptions' => array('style' => "text-align:left;"),
),
queryAll() returns array of rows, so it is actually array of arrays. Something like:
[
['ar_code' => 123],
]
If you want to query single value (for example 123), you should use queryScalar() - it will return value from first column of first row:
public static function getAR_code($actId) {
return Yii::app()->db->createCommand()
->select('ar_code')
->from('{{ar_codes}}')
->where('act_id=' . (int) $actId)
->queryScalar();
}
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();
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');
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();