how to use mysql query in yii framework - yii

I am new to yii framework using yii 1.1.14 First of all I didnt understand it. My target is to insert, select, update and delete data from database . Its very confusing for me.please give me some example .

Some examples
1.Insert query in YII2
$connection = Yii::$app->db;
$connection->createCommand()->insert('tbl_name', [
'column1' => Yii::$app->request->post('column1'),
'column2' => Yii::$app->request->post('column2'),
])->execute();
2.Update query
Yii::$app->db->createCommand()->update('tbl_name', [
'column1' => Yii::$app->request->post('column1'),
'column2' => Yii::$app->request->post('column2'),
],
'where_id ="'.$where.'" ')->execute();

I recommended you to use Gii, and use it to generate a Model of table.
For example, table: user(columns: id,name), Model: User.
You can insert or update data like the following:
$user = new User(); // Insert
// $user = User::find()->where(['id'=>'1'])->one(); // Update
$user->name = "Insert data";
$user->save();
See also http://www.yiiframework.com/doc-2.0/guide-start-gii.html

For the queries you can use Active Record and for CRUD you can use Gii

Related

Create a ActiveDataProvider based on ActiveRecord Relation in Yii2

I have a many-to-many relation setup using a junction table in MySQL. Table Article is related to Activity via table Article_Activity.
In model Article I have a relation setup like this
public function getActivities()
{
return $this->hasMany(Activity::className(), ['id' => 'activity_id'])
->viaTable('article_activity', ['article_id' => 'id']);
}
When rendering a view for one Article I would like to display a GridView of all Activities related to that Article.
The way most people seem to this is to create a ActiveDataProvider and insert a query into it that fetches related data but that feel a bit redundant since I have the relation setup in the model and there should be a way to get a dataprovider from that.
My question is: Is there a way to get a yii\data\ActiveDataProvider or yii\db\Query based on a instantiated models relation that can be used to display all related records in a GridView?
You can actually call it like this:
$dataProvider = new ActiveDataProvider([
'query' => $article->getActivities(),
]);
If you call the get method directly you get a yii\db\ActiveQueryInterface which is what you need to provide as query to the ActiveDataProvider.
When you call the activities attribute like $article->activities the ActiveQueryInterface is executed and you get the records from the query results.
Based on you Article model you have the activities relation that get multiple Activity related to you Article
a normal dataProvider like
$dataProvider = new ActiveDataProvider([
'query' => Article::find()->joinWith(['activities'])->
where(['your_column'=> $your_value]),
]);
return activeRecord whit also the related activities
you can refer to the related models inside the dataProvider
$models = $dataProvider->models; // this is a collection of model related to the dataProvider query
// so the firts model is $model=models[0]
then for each of this you can obtain acyivities
$activities = $model->activities;
or value
$my_activity_field = $model->activities->my_activity_field

How can I update itemname column using user id in table AuthAssignment Yii Framework

I use auth manager (RBAC) in Yii Framework and I have a problem.
I want to update column itemname using user id in table AuthAssignment .
I can insert to database with this code:Yii::app()->authManager->assign($model->role,$model->id);
but ı don't know how can I update this data in table AuthAssignment .
There is no update action provided for AuthAssignment. For updating column itemname, you should first 'revoke' your item from given RBAC GUI, then 'assign' your updated item.
Let me know if you face further query for the same.
I think, there is not update method in auth manager(RBAC).So we must use revoke method for delete and assign method for insert. I use following code in Usercontroller
public function assignRole($role,$id) {
$auth = Yii::app()->authManager;
$items = $auth->getRoles($id);
foreach ($items as $item) {
$auth->revoke($item->name, $id);
}
// assign new role to the user
$auth->assign($role, $id);
$auth->save();
}
Then I call following code for insert and update role to table
$this->assignRole($model->role,$model->id);

Yii CActiveDataProvider Relations

Anyone can enighten me, i am new to Yii. I have 3 tables
projects (id,name,status,created_by)
users (id,name)
project_users (id,project_id,user_id)
The condition is: Show all projects if created by current user or current user is a project member. I have already a working code for this.
$criteria=new CDbCriteria;
$criteria->join = ' LEFT JOIN project_users pu ON pu.project_id=t.id';
$criteria->addCondition('created_by='.Yii::app()->user->id.' OR pu.user_id='.Yii::app()->user->id);
$criteria->distinct = true;
$dataProvider=new CActiveDataProvider('Project',
array(
'pagination'=>array('pageSize'=>15),
'criteria'=> $criteria
)
);
But, id like to learn how can i get same result using "WITH" (relational AR query in Yii). I already tried but all failed. Please help thanks.
the relation on Project model file
projectUsers' => array(self::HAS_MANY, 'ProjectUsers', array('id'=>'project_id')),
$dataprovider should be
$dataProvider=new CActiveDataProvider('Project',
array(
'pagination'=>array('pageSize'=>15),
'criteria'=>array(
'with'=>array(
'projectUsers' => array('alias' => 'pu')
),
'condition' => 't.created_by='.Yii::app()->user->id.' OR pu.user_id='.Yii::app()->user->id,
'distinct'=>true,
'together'=>true,
),
)
);
Check out my picture. The criteria is more powerful than that, but you can understand the basically how to use
Small tip: If everything is new with you, just enable Yii log to see what the query is produced eventually, then you can troubleshoot the problem by yourself.

Get all data using CActiveDataProvider

I have a model InboxMessageHelper with relations like
'message', 'sender' and 'receiver' and I am using the following criteria to query data:
$model = new CActiveDataProvider('IndividualMessageHelper', array(
'criteria'=>array(
'condition'=>'receiver_id = '.Yii::app()->user->id,
'order'=>'message.created_at DESC',
'with'=>array('message', 'sender', 'receiver'),
'together'=>true,
),
));
I want to get all data (i.e. including the relations data) inside the controller and form a JSON, but the problem is that i cannot access related fields data. I can see that the data is available when I use
CVarDumper::dump()
when I try to encode $model->data then only data from current table gets encoded. How should I go about it?
I don't think CActiveDataProvider can be used in this way. You need to be working with the model. So you'll need something like this in your controller.
$models = IndividualMessageHelper::model()->findAll('receiver_id = '.Yii::app()->user->id);
foreach($models as $model){
$json[] = $model->getAttributes; //This won't get any model properties you've declared
yourself, only database columns
}
//Now get the related records and add them to the array.
array_push($json, $model->getRelated('message')->getAttributes());
array_push($json, $model->getRelated('sender')->getAttributes());
array_push($json, $model->getRelated('receiver')->getAttributes());
echo json_encode($json);

how to fetch data from db and display in views

I am new to yii framework.I have just create an app and I want to fetch data from DB based on some condition and then display that in views .For this I have tried few things in my controller :
if(isset($_GET['sku']))
{
$sku=$_GET['sku'];
$data=Products::model()->findAll("sku=$sku");
}
$this->render('checkout',array(
'data'=>$data,
));
and when in my views i try to print data as :
print_r($data);
I shows me a complex array , but i do not want that.
The thing which i want is I can get an array from controllers which includes the data return by query based on some condition and in my views using foreach i can display them according to my need.
So please suggest me some good ways of fetching data from db and can display them in my views.
Thanks !!
In your view use something like this:
<?php echo CHtml::encode($data->fieldname); ?>
Or better, use the Gii code generator to build your CRUD functions, and you will see several good examples for how to build these functions. Here is a link to a very good tutorial: http://www.yiiframework.com/doc/guide/1.1/en/quickstart.first-app
Try to use DAO instead Active Record
$sql = "SELECT * FROM `products` WHERE sku = ".Yii::app()->request->getParam('sku', 0);
$data = Yii::app()->db
->createCommand($sql)
->queryAll();
$this->render('checkout',array(
'data'=>$data,
));
You should have db component in config file(ex. config/main.php)
http://www.yiiframework.com/doc/guide/1.1/en/database.dao