yii get has_many relations count - php

How to get the count of childCompetency through childDomain which having has many relation
'childDomain' => array(self::HAS_MANY, 'SkillRelDomain', 'skill_id'),
'childCompetency' => array(self::HAS_MANY, 'SkillRelCompetency', 'domain_id'),

Here is a one to many (User:Post) relationship example in Yii 1
In case of post every post belongs to a user. So relation looks like this.
public function relations() {
return array(
'user'=>array(self::BELONGS_TO, 'User', 'iduser'),
);
}
Similarly, a user can have multiple posts. So relation for user as:
public function relations() {
return array(
'posts'=>array(self::HAS_MANY, 'Post', 'iduser'),
);
}
Now when you do a $user = User::model()->findByPk($id), you can have access to relation data also
you can call
foreach($user->posts as $post){
echo $post->name;
}

Related

how to extract this data in yii2 mysql

The data to be extracted are:
->select('ingreso.idingreso', 'ingreso.fecha_hora', 'persona.nombre', 'ingreso.tipo_comprobante', 'ingreso.serie_comprobante', 'ingreso.num_comprobante', 'ingreso.impuesto', 'ingreso.estado', 'SUM("ingreso.cantidad*precio_cantidad") AS total')
the relationships of the models in the tables:
table "ingreso"
public function relations()
{
return array(
'didingreso' => array(self::HAS_MANY,'detalle_ingreso', 'idingreso'),
);
}
table "detalle_ingreso"
public function relations()
{
return array(
'ingres' => array(self::HAS_ONE,'ingreso', 'idingreso'),
'articulo' => array(self::HAS_ONE,'articulo', 'idarticulo'),
);
}
table "articulo"
public function relations()
{
return array(
'idproveed' => array(self::HAS_MANY,'ingreso', 'idproveedor'),
);
}
table "persona"
public function relations()
{
return array(
'idproveed' => array(self::HAS_MANY,'ingreso', 'idproveedor'),
);
}
without the relationships I tried to do this:
$table = Ingreso::find()
->innerJoinWith('persona', 'ingreso.idproveedor = persona.idpersona')
->innerJoinWith('detalle_ingreso', 'ingreso.idingreso = detalle_ingreso.idingreso')
->select('ingreso.idingreso', 'ingreso.fecha_hora', 'ingreso.nombre', 'ingreso.tipo_comprobante', 'ingreso.serie_comprobante', 'ingreso.num_comprobante', 'ingreso.impuesto', 'ingreso.estado', 'SUM("detalle_ingreso.cantidad*detalle_ingreso.precio_venta") AS total')
->andWhere(["estado" => 'A'])
->orderBy(['ingreso.idingreso' => SORT_DESC])
->groupBy(['ingreso.idingreso', 'ingreso.fecha_hora', 'ingreso.nombre', 'ingreso.tipo_comprobante', 'ingreso.serie_comprobante', 'ingreso.num_comprobante', 'ingreso.impuesto', 'ingreso.estado']);
these are my tables:
the error that throws me apparently is when trying to access the result and is the following:
thanks for your help.
If you are using Yii2 you should use the relations statements from yii2 activeRecord.
Here the documentation
EDIT:
You should create all realtions that you need individually and then create a mixed query with with
Your Model:
public function getIngreso(){
return $this->hasMany(Ingreso::className(), ['id' => 'id_ingreso']);
}
public function getDetalleingreso(){
return $this->hasMany(DetalleIngreso::className(), ['id' => 'id_detalleingreso']);
}
In your controller:
$results = $model->find()->select('foo')->with(['ingreso', 'detalleingreso'])->all();

How to handle a create form with one to many relation in Yii?

I work with Yii 1.1. I wish to make a create form, which creates a module. A module belongs to one user. A user has many modules.
tbl_user
----------
id
firstName
lastName
email
password
role
and
tbl_user_module
----------
id
name
academicYear
....
userId [FOREIGN KEY]
The relations in models are set up as follow:
Module.php
public function relations()
{
return array(
'user' => array(self::BELONGS_TO, 'User', 'userId'),
);
}
User.php
public function relations()
{
return array(
'module' => array(self::HAS_MANY, 'Module', 'userId'),
);
}
A user uses a from to create a module, which belongs to him (logged in user). In the controller, I need to assign the userId foreign key as the logged in user.
public function actionCreate()
{
$module = new Module();
// collect user input data
if(isset($_POST['Module']))
{
$module->attributes=$_POST['Module'];
$module->userId = Yii::app()->user->id; //assigned userID as logged in user
if($module->validate())
{
if($module->save())
{
$this->redirect(array('home/index'));
}
}
}
//render
$this->render('create',array('model'=>$module));
}
The form is not saved and throws an error:
Property "Module.$userId" is not defined.
Obviously, I am not doing it right. How do I properly save a one-to-many relations in a form?
Solved, I had a typo in Module.php!

CakePhp multiple table data fetch on single page

I am new in cakePHP try to create a blog site where user add blog after category select, I have one categories table : fields: category_id, name and posts table : fields : id, category_id , title, body.
I want to fetch all categories to a dropdown list. When user add new post they have to select category first then he is able to post anything..
My PostsController:
<?php
class PostsController extends AppController{
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session','Paginator');
public function index(){
$this->Paginator->setting = array(
'limit' =>'10',
'order' => array('Post.id' =>'Desc')
/*'conditions' => array(
'Post.user_id' => AuthComponent::user(id)
)*/
);
$arrPosts = $this->Paginator->paginate('Post');
$this->set('posts', $arrPosts);
}
public function view($id = null){
if(!$id){
throw new NotFoundException(__("Error Processing Request ID"));
}
$post =$this->Post->findById($id);
if(!$post){
throw new NotFoundException(__("Error Processing Request POST"));
}
$this->set('post',$post);
}
public function add(){
// HERE I want to fetch all categoryies from categories table and want to send to view
if($this->request->is('post')){
$this->Post->create();
if($this->Post->save($this->request->data)){
$this->Session->setFlash(__('Blog Posted Sucessfully'));
return $this->redirect(array('action' => 'index'));
}else{
$this->Session->setFlash(__('Unable to Post Blog '));
}
}
}
}
?>
I want to show my category in add form:
Please help me ...
In your controller action you need to use $this->set() to set a View variable. As long as you've got your associations setup correctly in your Post model you should then be able to use:-
$this->set('categories', $this->Post->Category->find('list'));
Cake's FormHelper should automatically know that the Post.category_id form field wants to be a select input with $categories as the options.
One further point, it would be better to set the view variables after processing the form as you won't need them if it saves correctly and so can reduce the number of database queries by 1.
If you use find('all') to retrieve the categories you will need to convert it into the format used by find('list') which can easily be done using Hash::combine():-
$categories = $this->Post->Category->find('all');
$this->set(
'categories',
Hash::combine($categories, '{n}.Category.id', '{n}.Category.name')
);
The only real value in doing this is if you need $categories for something else.
public function add(){
/*Here get the category list & set the view (ctp file)*/
$this->set('categories', $this->Post->Category->find('list'));
if($this->request->is('post')){
$this->Post->create();
if($this->Post->save($this->request->data)){
$this->Session->setFlash(__('Blog Posted Sucessfully'));
return $this->redirect(array('action' => 'index'));
}else{
$this->Session->setFlash(__('Unable to Post Blog '));
}
}
}
//Set The dropdown in ctp file
$this->Form->input('category_id', array('type'=>'select', 'options'=>'categories'));

relation using BELONGS_TO with user table

I'm trying to join my comment table with my user table like this comment.userId=user.id
unfortunately when i print_r($this->user); i get nothing. what am i doing wrong here?
in my comment model
public function relations()
{
return array(
'user' => array(self::BELONGS_TO, $this->module->user, 'userId'),
);
}
public function getLastName()
{
print_r($this->user);
die;
return is_null($this->user) ? '' : $this->user->{$this->module->lastNameAttribute};
}
where
$this->module->user = 'User'; //User is the model name
and
$this->module->lastNameAttribute = 'last_name';
in my view
$comments = $model->getCommentDataProvider();
$comments->setPagination(false);
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$comments,
'itemView'=>'application.modules.comment.views.comment._view', //view file location
'emptyText' => '<div class="alert alert-info">No comments yet.</div>',
'summaryText' => '<h4>'.Yii::t('commentTitle','{n} comment|{n} comments',$comments->totalItemCount).'</h4>'
));
I see a small typo, maybe you mistaken while making a post:
comment.userid=user.id
here it's userid and in relation you referenced it with userId
check it out please
EDIT - after question edit
I'm not familiar with CommentableBehavior but it seems to me that you need to eager load User model with each Comment:
$comments = Yii::createComponent($this->module->commentModelClass)->with('user')->findAll($this->getCommentCriteria());
I added with('user') in getComments() method

Yii CActiveDataProvider MANY::MANY

i got 2 models: Project and Users connected with (User.php):
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
"projects"=>array(self::MANY_MANY, 'Project','projects_users(user_id, project_id)'),
);
}
I want to show all users in CActiveDataProvider who are not connected with project. How can i do it?
I found solution:
$criteria=new CDbCriteria;
foreach($model->users as $cur) {
$criteria->addCondition("ID != ".$cur->ID);
}
$users=User::model()->findAll($criteria);
$dataProvider2=new CActiveDataProvider('User');
$dataProvider2->data = $users;
Try this:
$users = User::model()->with('projects')->findAll(array(
'together' => true,
'condition' => 'projects.id IS NULL',
));

Categories