Join query retrieving data from only one table cakephp 3 - php

I am new to cakephp. I am usign query builder to fetch details from two tables using join in cakephp query builder.But the query i am writing is fetching details only from one table. Need help to get data from other table as well.
This is my code to fetch data by joining two tables:
public function edit($id = null) {
$events_table = TableRegistry::get('Events');
$events = $events_table->find('all')
->hydrate(false)
->join([
'CourseType'=> [
'table' => 'coursetype',
'type' => 'LEFT',
'conditions' => 'Events.type = CourseType.coursetype_id',
]
])->where(['Events.id' => $id]);
$event = $events->toArray();
$this->set('event', $event);
}
As a result i am getting only details from events table. But i need data from coursetype also.Any help is appreciated. Thank you.

Manually adding joins won't cause any additional data to be selected, you'd have to do that on your own by specifying the fields to be selected via the select() method.
$events = $events_table
->find('all')
->hydrate(false)
->select($events_table)
// either add the fields one by one, or pass a table object
// as above to select all fields of the table
->select(['CourseType.id', 'CourseType.xyz', /* ... */])
// ...
I'd suggest to use use containments instead, ie setup the required association if not already present, and then simply use contain():
$events = $events_table
->find('all')
->hydrate(false)
->contain('CourseType')
->where(['Events.id' => $id]);
See also
Cookbook > Database Access & ORM > Query Builder > Selecting Data
Cookbook > Database Access & ORM > Query Builder > Loading Associations

your solution here: CakePHP find method with JOIN

Related

How can i select all the data from the two tables "incoming_calls" and the "outgoing_calls" tables in Laravel 5.6

I Want to select all the calls from the incoming_calls table and the outgoing_calls table together. Basically i am creating api and i want to get the data from these two tables and to paginate them.
How can i do that? Anyone!
Thanks in advance!
So, about your case, you'll need to create pagination manually (more info [FR]), so collection should have the same structure.
This code can do the thing.
$calls = IncomingCall::all()->merge(OutgoingCall::all());
//creating of pagination
$page = \Illuminate\Support\Facades\Input::get('page', 1);
$perPage = 10;
$calls = new \Illuminate\Pagination\Paginator(
$calls->slice(($page - 1) * $perPage),
$perPage,
$page,
[
'path' => \Illuminate\Pagination\Paginator::resolveCurrentPath()
]
);
Do the two tables have a field in common? Or do you want the two results separate?
To select data and paginate simply use
$users = DB::table('users')->paginate(15);
See Laravel Docs or you can also use Laravel Eloquent

ActiveQuery count() and all() return different results

I have a query:
$query = Products::find();
$query->joinWith('vendor', true, 'LEFT JOIN');
$query->joinWith('values', true,'LEFT JOIN');
$query->where(['<>', 'stock', 7]);
$query->andWhere(['category_id' => $model->id]);
if (!empty($activeVendors))
$query->andWhere(['lan_vendors.id' => array_flip($activeVendors)]);
if (!empty($activeValues)){
$query->andWhere(['lan_products_values.value_id' => $activeValues]);
}
$totalProducts = $query->count();
$products = $query->all();
In result:
$totalProducts = 12;
count($products) = 3;
I can not solve this problem. Reading the documentation did not help. Is there something wrong with the database itself?
your left join statements generate duplicate rows.
after a the query runs yii removes duplicate data and creates a usable array of uniqe Product models
the duplicate rows are not avoidable in your case since you enforce eager loading with left join
$query->joinWith('vendor', true, 'LEFT JOIN');
$query->joinWith('values', true,'LEFT JOIN');
you can try to run something like this to adjust the relations to your conditions, and follow the generated queries
in the debug log,
$query->with([
'vendor' => function (\yii\db\ActiveQuery $query) use ($activeVendors) {
$query->andFilterWhere(['lan_vendors.id' => array_flip($activeVendors)]);
},
'values' => function (\yii\db\ActiveQuery $query) use ($activeValues) {
$query->andWhere(['lan_products_values.value_id' => $activeValues]);
},
])
also follow the generated queries in the debug log, it's a usefull way of figuring out what happens in the two cases
Because you are joining additional tables here most probably you have got dupicated results - you can check it by running this query manually outside of Yii.
Query count() is showing you all the rows fetched from database (with duplicates).
all() on the other hand takes the fetched rows and while populating the Yii 2 models it removes duplicates so you have got unique ones.

Yii2 Converting model objects to array with ArrayHelper::toArray()

I am working in YII2 Framework on the following query
SELECT T.id, T.name, T.status, IFNULL(T.image,'no-image.png') as DP
FROM TABLE_NAME T;
here is my code
$modelTeam = Teams::find()
->select(
['T.id', 'T.name', 'T.status', 'IFNULL(T.image,"no-image.png") as DP']
)
->from('{{%teams}} T')
->all();
Edit:
The result set does not include DP column at all why is that so, and how can I do that.
Edit 2:
While telling that the results do not include the DP column I missed a piece of important information that I was using the ArrayHelper::toArray() to convert the model object to an array and then iterate over it
$results=ArrayHelper::toArray($modelTeam);
The actual problem is not where I was thinking it is, the query is alright, I used ArrayHelper::toArray($modelTeam) method to convert the model object to an array to further iterate over the array and display all the records, and that is where the problem lies.
I needed to use the second parameter $properties for the ArrayHelper::toArray(). The second argument converts properties mapping per class, as it has problems displaying the custom declared public properties of a model and the DP is declared public inside the Teams model as it is an alias in the ActiveRecrod query.
$modelTeam = Teams::find()->
select(['TM.id', 'TM.name', 'TM.status'])
->addSelect([new \yii\db\Expression('IFNULL(TM.image,\'no-image.png\') AS DP')])
->from('{{%teams}} TM')->all();
$results = ArrayHelper::toArray($modelTeam, [
'common\models\Teams' => [
'id',
'name',
'status',
'DP',
],
]);
$modelTeam = Teams::find()
->select(['T.id', 'T.name', 'T.status'])
->addSelect([new Expression('IFNULL(T.image,"no-image.png") as DP')])
->from('{{%teams}} T')
->all();
$arrTeam = $modelTeam->asArray()->all();
To use IFNULL in a select with Yii2 you must create a new expression.
$modelTeam = Teams::find()
->select(['T.id', 'T.name', 'T.status'])
->addSelect([new Expression('IFNULL(T.image,"no-image.png") as DP')])
->from('{{%teams}} T')
->all()

How do I agree a new element on a array after do a query?

I'm trying to include a new element on a array that is filled with a query result.
For example, I have an array called $event with $event['name'], $event['date'], $event['price'].
Now, I want to add $event['category']. This one is not declared on DB event table, but $event is an array of my code. It not depends of the DB event table, no?
So... how I can put $event['cateogory'] inside event in my Class code of CodeIgniter?
I tried to put it directly, and the error show that "category" index is not defined.
$events = $this->Event_model->get_all_events();
foreach ($events as $event) {
$event['category'] = $this->Category_model->get_category($event['idCategory']);
}
$data{
'events' => $events,
}
$this->load->view('events_list',$data);
Thank you all
Rather than trying to iterate over every result and adding the category (which you can do if you follow the comment made by Tularis), you should let SQL add the category by using SQL Joins.
In the Code Igniter Documentation on Active Records, you'll find information about joining Tables in Code Igniter.
Here's a simple example from the documentation adjustet to your needs:
$this->db->select('*');
$this->db->from('events');
$this->db->join('categories', 'categories.id = events.idCategory');
$query = $this->db->get();
// Produces:
// SELECT * FROM blogs
// JOIN comments ON comments.id = blogs.id

How to get the corresponding data in drop down from database in yii

I have a field in my form 'update_job' named as 'job_category',which is a dropdownlist and has been stored in main table as category_id,and the table is related to another table 'category'.
My first question is how to write the joint query to get the category as well:I have written code to get all data and it works fine:but how to write a join query to get the category as well?
//code//
public function actionDisplayJob()
{
if (isset($_GET['id'])) {
$id = $_GET['id'];
}
$model = DisplayJob::model()->find(array(
'select' => array('posted_by', 'title', 'key_skills'), "condition" => "id=$id"
));
$params = array('model' => $model);
$this->render('update', $params);
}
Second,What should I do to keep data selected in dropdown list from database while editng the data?
You can set relations in your model. Assuming you have done this, you can use 'with' to join the related model (tabel):
$model = DisplayJob::model()->with('category')->find(array(
'select' => array('posted_by', 'title', 'key_skills'), "condition" => "id=$id"
));
More information about using relations you can find here:
http://www.yiiframework.com/doc/guide/1.1/en/database.arr

Categories