Adding another field from another controller into an array - mysql

Hey at the moment we have an arrray selecting all from one table (relationship) and we need to put account_name from the Accounts table in that array. How would we do so?
Our Relationship table has (id, receiver_id, sender_id, active, expiry_date). Receiver_id and sender_id both are the foreign keys for account_id.
At the moment it works fine but prints the ids of the receiver and sender, we want the account_name from Account table to be there instead.
Here is our function, view and model:
Function:
//retrieve Account Id of current User
$accountid=$this->Auth->user('account_id');
//Conditions
$conditions=array("OR"=> array(
'Relationship.sender_id' => $accountid,
'Relationship.receiver_id' => $accountid));
//Find all Invoices where receiver_id = accountid
$relationships=$this->Relationship->find('all', array(
'conditions' => $conditions));
debug($relationships);
$this->set('accountid', $accountid);
$this->set('relationship', $relationships);
}
View:
<table>
<tr>
<th>Relationship #</th>
<th>Sender</th>
<th>Receiver</th>
<th>Expiry Date</th>
<th>Status</th>
</tr>
<?php foreach($relationship as $relationships):?>
<?php
if($relationships['Relationship']['active']==1)
{
$status = 'Active';
}
else if($relationships['Relationship']['active']==0)
{
$status = 'Not Active';
}
?>
<tr>
<td align='center'><?php echo $relationships['Relationship']['id']; ?></td>
<td align='center'><?php echo $relationships['Relationship']['sender_id']; ?></td>
<td align='center'><?php echo $relationships['Relationship']['receiver_id']; ?></td>
<td align='center'><?php echo date('d.m.Y', strtotime($relationships['Relationship']['expiry_date'])); ?></td>
<td align='center'><?php echo $status ?></td>
</tr>
<?php endforeach; ?>
</table>
Relationship Model:
class Relationship extends AppModel
{
var $name = 'Relationship';
public $useTable = 'relationships';
public $primaryKey = 'id';
/*
public $hasMany = array(
'Invoice' =>
array(
'className' => 'Invoice',
'joinTable' => 'invoice',
'foreignKey' => 'invoice_id'));*/
//fix this code
public $belongsTo = array(
'User' =>array(
'className' => 'User',
'foreignKey' =>'receiver_id',
'associationForeignKey' => 'accounts_id',
));
var $validate = array(
'date' => array(
'rule' => array(
'datevalidation',
'systemDate'
),
'message' => 'Current Date and System Date is mismatched'
),
'receiver_id' => array(
'userExists' => array(
'rule' => array(
'userExists',
),
'message' => 'That username doesnt exist.'
),
),
);
function datevalidation($field = array(), $compare_field = null)
{
if ($field['date'] > $compare_field)
return TRUE;
else
return FALSE;
}
function accountExists($check)
{
$accountExists = $this->Account->find('count', array('conditions' => array('Account.id'=>$check)));
if ($accountExists == 1) {
return TRUE;
}
else
return FALSE;
}
}

Note it's not another field from another "controller" but rather another model.
There are a number of ways you could do this:
You could use joins on the find() method: http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#joining-tables
Or you could probably also use bindModel(), which I find particularly useful: http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly
Scour the cookbook! Although sometimes tedious, it really is extremely helpful. I had to hack around quite a bit before I got a decent understanding of how Cake works.

Related

How to Get WooCommerce Product Name with WP_Query?

I am trying to use this code on "Wp All Import". If there is a product name in the database, that product should be omitted, but the code will not work as is. What do I need to do for the code to work?
add_filter('wp_all_import_is_post_to_create', 'create_only_if_unique_custom_field', 10, 3);
function create_only_if_unique_custom_field( $continue_import, $data, $import_id ) {
// Only run for import ID 1.
if ( $import_id == 33 || $import_id == 34 ) {
// The custom field to check.
$key_to_look_up = "post_title";
// The value to check where 'num' is the element name.
$value_to_look_up = $data['name'];
// Prepare the WP_Query arguments
$args = array (
// Set the post type being imported.
'post_type' => array( 'post' ),
// Check our custom field for our value.
'meta_query' => array(array(
'key' => $key_to_look_up,
'value' => $value_to_look_up,
)),
);
// Run the query and do not create post if custom field value is duplicated.
$query = new WP_Query( $args );
return !($query->have_posts());
} else {
// Take no action if a different import ID is running.
return $continue_import;
}
}
You can do like this.
<?php
$params = array('posts_per_page' => 5);
$wc_query = new WP_Query($params);
?>
<?php if ($wc_query->have_posts()) : ?>
<?php while ($wc_query->have_posts()) :
$wc_query->the_post(); ?>
<?php the_title(); ?>
<?php endwhile; ?>
<?php wp_reset_postdata();?>
<?php else: ?>
<p>
<?php _e( 'No Products' ); ?>
</p>
<?php endif; ?>
There are some ways to show the different types of Woocommerce product names with WP_Query.
<?php
//Pulling WooCommerce Products instead of WordPress Posts, Use this param
$params = array(
'posts_per_page' => 5,
'post_type' => 'product'
);
//Displaying products of a given price range, use this param
$params = array(
'posts_per_page' => 100,
'post_type' => array('product', 'product_variation'),
'meta_query' => array(
'relation' => 'OR',
array(
'key' => '_price',
'value' => 5,
'compare' => '<=',
'type' => 'NUMERIC'
),
array(
'key' => '_sales_price',
'value' => 5,
'compare' => '<=',
'type' => 'NUMERIC'
)
)
);
//Displaying available products only, use this param
$params = array(
'posts_per_page' => 5,
'post_type' => array('product', 'product_variation'),
'meta_query' => array(
array(
'key' => '_price',
'value' => 5,
'compare' => '<',
'type' => 'NUMERIC'
),
array(
'key' => '_stock_status',
'value' => 'instock'
)
)
);
$wc_query = new WP_Query($params);
if ($wc_query->have_posts()) :
while ($wc_query->have_posts()) :
$wc_query->the_post();
the_title();
endwhile;
endif;
Also will help you the article https://www.gavick.com/blog/wp_query-woocommerce-products
Thank you
This variable controls the title.
// Xml file column name
$value = = $data['product_title'];
// Get wpdb product title
$posts = get_posts([
'post_type' => 'product',
'title' => $value,
]);

Yii - Display Many to Many Attribute in DetailView

I have these three tables as shown below
courses and instructors tables are linked together in course_instructors
Model: Course
public function attributeLabels()
{
return [
'id' => Yii::t('course', 'Course ID'),
'course_name' => Yii::t('course', 'Course Name'),
'course_code' => Yii::t('course', 'Course Code'),
];
}
public function getCourseInstructors()
{
return $this->hasMany(CourseInstructors::className(), ['course_id' => 'id']);
}
and also
Model:Instructor
public function attributeLabels()
{
return [
'instructor_id' => Yii::t('ins', 'Instructor ID'),
'first_name' => Yii::t('ins', 'First Name'),
'middle_name' => Yii::t('ins', 'Middle Name'),
'last_name' => Yii::t('ins', 'Last Name'),
];
}
function getInstructorFullName()
{
return ($this->first_name." ".$this->middle_name." ".$this->last_name);
}
Then,
Model: CourseInstructors
public function attributeLabels()
{
return [
'id' => 'Course Instructor ID',
'course_id' => 'Course',
'instructor_id' => 'Course Instructor',
'remark' => 'Remark',
];
}
public function getCourses()
{
return $this->hasOne(Courses::className(), ['id' => 'course_id']);
}
public function getInstructors()
{
return $this->hasOne(Instructors::className(), ['instructor_id' => 'instructor_id']);
}
CourseControllers
public function actionView($id)
{
$model = $this->findModel($id);
$courseinstructors = $model->courseInstructors;
return $this->render('view', [
'model' => $model,
'courseinstructors' => $courseinstructors,
]);
}
Detail View: course
<?= DetailView::widget([
'model' => $model,
'options'=>['class'=>'table detail-view'],
'attributes' => [
'course_name',
'course_code',
],
]) ?>
<h2>Details</h2>
<table class="receipt-details table">
<tr>
<th>ID</th>
<th>Instructor Name</th>
<th>Remark</th>
</tr>
<?php foreach($model->courseInstructors as $courseInstructor) :?>
<tr>
<td><?= $courseInstructor->id ?></td>
<td><?= $courseInstructor->instructor_id ?></td>
<td><?= $courseInstructor->remark ?></td>
</tr>
<?php endforeach; ?>
</table>
From my Course Detail view, I want to display the instructor fullname
function getInstructorFullName()
{
return ($this->first_name." ".$this->middle_name." ".$this->last_name);
}
instead of the instructor_id in the Course Detail View
<td><?= $courseInstructor->instructor_id ?></td
This is what am getting
The question is how do I display the instructor full name in the course detail view instead of the instructor_id, since it is many to many.
You should use the framework power and consume the relations for the ActiveRecord models. Change your line from
<td><?= $courseInstructor->instructor_id ?></td>
to the following
<td><?= $courseInstructor->instructors->first_name.' '.$courseInstructor->instructors->last_name ?></td>
a better way would be to add the following method inside the model Instructors
public function getFullName(){
return $this->first_name.' '.$this->middle_name.' '.$this->last_name;
}
and then use it like
<td><?= $courseInstructor->instructors->fullName ?></td>
This should work in the Detail View:
<td><?= $courseInstructor->instructors->first_name ?></td> for first name.
<td><?= $courseInstructor->instructors->last_name ?></td> for last name.
You can join the name string to make a full name.
This comes from
public function getInstructors()
{
return $this->hasOne(Instructors::className(), ['instructor_id' => 'instructor_id']);
}
Let me know if it works for you.

Yii2 display data after join

I have joined 2 table, now I want to show the name of categories in field <th>Categories name</th>. How can I do that with <?php foreach ($posts as $post){ ?> ? Do i render like <?=$post->categories.name?> ? I'm stuck here.
Thank you.
My controller:
public function actionIndex()
{
$query = posts::find()->leftJoin('categories', 'posts.cate_id = categories.id');
$cates = Categories::find()->all();
$posts= $query->orderBy(['create_date' => SORT_DESC])->all();
$images = Images::find()->all();
$searchModel = new PostsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'posts' => $posts,
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
'cates' => $cates,
'images' => $images,
]);
}
My view:
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Create Date</th>
</thead>
<tbody>
<?php foreach ($posts as $post){ ?>
<tr>
<td><?= $post->id ?></td>
<th><?= Html::a($post->name, ['post/view', 'id'=>$post->id]) ?></th>
<td><?= $post->create_date ?></td>
</tr>
<?php } ?>
</tbody>
Loop through the categories just as with posts. Its the same principle.
foreach($posts as $post)
foreach($post->categories as $category)
echo $category->name;
This is based on the assumption you have defined the proper relations in the model.
I.e. through foreign key:
public function getCategories()
{
return $this->hasMany(Category::className(), ['post_id' => 'id']);
}
You seem to have it the other way around. You can have category_id in post, but then its limited to one category. Unless, you store the ids in the field seperated by a delimeter. But that option requires a bit more work.

cakephp instead of user_id how do I get for instance username in the view

I have 3 tables: users, comments and videos.
In my videos view.ctp I can't get the username displayed, only the user_id.
I can't figure it out, can someone point me in the right direction?
User model:
public $hasMany = array(
'Comment' => array(
'className' => 'Comment',
'foreignKey' => 'user_id',
'dependent' => false
),
}
Video model:
public $hasMany = array(
'Comment' => array(
'className' => 'Comment',
'foreignKey' => 'video_id',
'dependent' => false
),
}
Comment model:
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
),
'Video' => array(
'className' => 'Video',
'foreignKey' => 'video_id'
)
);
}
Videos view.ctp
<?php if (!empty($video['Comment'])): ?>
<?php foreach ($video['Comment'] as $comment): ?>
<p><?php echo $comment['comment_created']; ?></p>
<p><?php echo $comment['User']['user_username']; ?></p>
<p><?php echo $comment['user_id']; ?></p>
<p><?php echo $comment['comment_body']; ?></p>
<?php endforeach; ?>
<?php endif; ?>
VideosController
public function view($id = null) {
$this->loadModel('Comment');
if (!$this->Video->exists($id)) {
throw new NotFoundException(__('Invalid video'));
}
$options = array('conditions' => array('Video.' . $this->Video->primaryKey => $id));
$this->set('video', $this->Video->find('first', $options));
$current_user = $this->Auth->user('user_id');
if ($this->request->is('post')) {
$this->Comment->create();
/*save the current's user id in database*/
$this->Comment->set('user_id', $current_user);
/*save the current's video id in database*/
$this->Comment->set('video_id', $id);
if ($this->Comment->save($this->request->data)) {
$this->Session->setFlash(__('You\'re comment has been placed.'));
return $this->redirect(array('action' => 'view/' . $id));
} else {
$this->Session->setFlash(__('You\'re comment could not be placed. Please, try again.'));
}
}
$this->set(compact('users', 'videos'));
}
Solution:
In the controller:
$comments = $this->Video->Comment->find('all', array('conditions' => array('Comment.video_id' => $id)));
In the view:
<?php foreach ($comments as $comment): ?>
<p><?php echo $comment['User']['user_username']; ?></p>
<p><?php echo $comment['Comment']['comment_created']; ?></p>
<p><?php echo $comment['Comment']['comment_body']; ?></p>
<?php endforeach; ?>

yii 1 relation not working in CGridView

I am trying to get relation where companies table have primary key companyID and division table have Foreign key companyID , what I need in where clause is WHERE companies.companyID = division.companies
relation in my model is :
public function relations()
{
return array(
'company' => array(self::BELONGS_TO, 'Companies', 'CompanyID'),
);
}
My Model->search() function is
public function search()
{
$criteria=new CDbCriteria;
$criteria->with ='company';
$criteria->compare('company.CompanyID', $this->CompanyID, true );
$criteria->compare('DivisionID',$this->DivisionID, true);
$criteria->compare('CompanyID',$this->CompanyID, true);
$criteria->compare('Name',$this->Name,true, true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
and my admin.php view is:
<?php
$this->breadcrumbs = array(
'Divisions' => array('index'),
'Manage',
);
$this->menu = array(
array('label' => 'List Divisions', 'url' => array('index')),
array('label' => 'Create Divisions', 'url' => array('create')),
);
");
?>
<div class="row">
<?php
$this->renderPartial('_dropdownfilter', array(
'model' => $model,
));
?>
</div><!-- end dropdown partial form -->
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'divisions-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
'CompanyID',
'DivisionID',
'Name',
array(
'class' => 'CButtonColumn',
),
),
));
?>
You need to add together=true to your criteria.
$criteria->together = true;
It'll add join to query. Some information about lazy loading http://www.yiiframework.com/wiki/527/relational-query-lazy-loading-and-eager-loading-with-and-together/
If you want to display company name,just do this in view.Don't change anything in model->search().
array(
'name'=>'Name',
'value'=>$model->company->name //here name is column name in company table.
),
In your gridview code do the following changes.
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'divisions-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
array(
'name' => 'companies',//fied from division table which refers to companyId from company table.
'header' => 'Company',
'value' => '$data->company->company_name'
),
'CompanyID',
'DivisionID',
'Name',
array(
'class' => 'CButtonColumn',
),
),
));
And in your model->search()
public function search()
{
$criteria=new CDbCriteria;
$criteria->with ='company';
$criteria->compare('company.company_name', $this->companies, true );
$criteria->compare('DivisionID',$this->DivisionID, true);
$criteria->compare('CompanyID',$this->CompanyID, true);
$criteria->compare('Name',$this->Name,true, true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}