Laravel: Nesting query join results in a sub array - php

NOTE Please do not suggest using Eloquent, this is specifically for the Laravel query builder.
For performance reasons we are using Query Builder to retrieve results from a table:
DB::table('posts')->get();
If we then want to join a relation onto that query:
DB:table('posts')
->leftJoin('comments', 'posts.id', '=', 'comments.post_id')
->get();
The results are merged into the array of each post:
[
'id' => 1,
'title' => 'My Blog Post',
'content' => '<h1>This is a post</h1><p>hello world</p>',
'post_author' => 'Billy',
'comment' => 'This is a comment',
'comment_author' => 'Andrew',
]
How can we have the joined results placed into a nested array? Such as:
[
'id' => 1,
'title' => 'My Blog Post',
'content' => '<h1>This is a post</h1><p>hello world</p>',
'post_author' => 'Billy',
'comment' => [
'id' => 22,
'comment' => 'This is a comment',
'comment_author' => 'Andrew',
],
]

Dont think its doable out of the box without Eloquent.
You can go the primitive route:
$results = DB:table('posts')
->leftJoin('comments', 'posts.id', '=', 'comments.post_id')
->select('posts.*', 'comments.*', 'comments.id as comments_id')
->get();
foreach($results as &$result)
{
$result['comment'] = [
'id' => $result['comment_id'],
'comment' => $result['comment'],
'comment_author' => $result['comment_author']
];
unset($result['comment_author'], $result['comment_id']);
}

Since you work with DB facade and not Eloquent, and cannot use built-in with() method, you have to implement it yourself:
$posts = DB::table('posts')->get()->toArray();
$comments = DB::table('comments')->get()->toArray();
foreach($posts as &$post)
{
$post->comments = array_filter($comments, function($comment) use ($post) {
return $comment->post_id === $post->id;
});
}
return $posts;
If you want to get rid of post_id for comments entries, you can do:
$posts = DB::table('posts')->get()->toArray();
$comments = DB::table('comments')->get()->toArray();
foreach($posts as &$post)
{
$comments = array_filter($comments, function($comment) use ($post) {
return $comment->post_id === $post->id;
});
$post->comments = array_map(function ($comment) {
unset($comment->id);
return $comment;
}, $comments);
}
return $posts;
(I guess the runtime would be similar to with(), since after-all MySql does not provide this functionality out-of-the-box).

Here some new information:
$data= $DB->select("select posts.*,comments from posts left join comments on posts.id = comments.post_id");
I am not sure it is work or not but you can try

You can try with this
$data= $DB->select("select *,(select json_agg(datas) from (select * from comments where posts.id=comments.post_id) as datas) as comments from posts;");
But you may need to decode at comments as well

Related

How to use OR condition here

I have a table records and another table categories
I want to get get all the records in this categories
$all_categories = '5,6,7,8';
So I am using this code:
$query = $this->Records->find('all',[
'contain' => ['Categories']
]);
if(!empty($search)){
$query->where(['Records.title LIKE' => '%'.$search.'%']);
}
if(!empty($wilaya)){
$query->where(['Records.adresse LIKE' => '%'.$wilaya.'%']);
}
if(!empty($cat)){
$query->where(['Records.category_id =' => $cat]);
} else {
$categories_array = explode(',',$all_categories);
foreach($categories_array as $category) {
$query->where(['Records.category_id =' => $category]);
}
}
When I use this, I'm getting AND-conditions by default.
How can I get OR-conditions instead?
Use IN:
$all_categories = '5,6,7,8';
$categories_array = explode(',',$all_categories);
$query->where(['Records.category_id IN' => $categories_array]);
This should work:
$all_categories = '5,6,7,8';
$array=explode(',',$all_categories);
$query->where(['Records.category_id' => $array], ['Records.category_id' => 'integer[]']);
Note: Edited answer to add information about the column data type. Won't work without this in CakePHP 3.x.
This equals to:
$all_categories = '5,6,7,8';
$array=explode(',',$all_categories);
$query->where(['Records.category_id IN' => $array]);
See Automatically Creating IN Clauses.

How to make associative array using PHP for loop to use in Yii 2 array map()?

I would like to make an associative array using PHP for loop to use in Yii2 map() method.
The array will look like in bellow format-
$listArray = [
['id' => '1', 'name' => 'Peter/5'],
['id' => '2', 'name' => 'John/7'],
['id' => '3', 'name' => 'Kamel/9'],
];
The id and name will be changed through each iteration of the loop. Here, the name will always hold customized value after some calculation inside the loop.
Finally, the list will be used in map() method like as following
$listData=ArrayHelper::map($listArray,'id','name');
I can use map() method directly after using the Active Record to find the list array and then use that in map() method. But it does not a give me way to use custom value for the name attribute.
$listArray = UserList::find()
->where(['status' => 1])
->orderBy('name')
->all();
$listData=ArrayHelper::map($listArray,'id','name');
How can achieve this? Direct source code example would be really great for me.
Thanks in advance.
I'm assuming you want to query an ActiveRecord for data then transfer the data into a simple array.
$listData = [];
$listArray = UserList::find()
->where(['status' => 1])
->orderBy('name')
->all();
foreach($listArray as $user){
$customName = $user->name . $this->someCalculation();
$listData[] = ["id" => $user->id, "name" => $customName];
}
Or you could use the ArrayHelper class like this:
$listArray = UserList::find()
->where(['status' => 1])
->orderBy('name')
->all();
$listData = ArrayHelper::toArray($listArray , [
'app\models\UserList' => [
'id',
'name' => function ($listArray ) {
return $listArray->word . strlen($listArray->word); // custom code here
},
],
]);
I think the preferred way of doing this by defining custom calculation rule in UserList model as:
public function getCustomRuleForUser(){
// Do what ever you want to do with your user name.
return $this->name.'Your custom rule for name';
}
And use as:
$userList = UserList::find()->all();
$listData=ArrayHelper::map($userList,'id','customRuleForUser');
Now, you have your custom rule for username list in $listData.
$model_userprofile = UserProfile::find()->where(['user_id' => Yii::$app->user->id])->one();
$model_userprofile1 = UserProfile::find()
->select('user_id')
->where(['group_id' => $model_userprofile->group_id])->all();
$listData = [];
foreach($model_userprofile1 as $user){
$id = $user->user_id;
$listData[] = ["id" => $id];
}
$dataProvider = new ActiveDataProvider
([
'query' => User::find()
->select('id,username,email')
->Where(['id' => $listData])
->orderBy(['id' => SORT_DESC]),
'pagination' => ['pagesize' => 15]]);
return $this->render('index',['dataProvider'=> $dataProvider]);

Laravel 4 paginate and orderBy

Normaly I call my database like this :
$data = array(
'one' => MyORM::paginate($this->per_page),
);
return View::make('project.index')->with($data);
But I also want to use an OrderBy so I can use:
$data = array(
'test' => MyORM::orderBy('date', 'DESC')->get(),
);
return View::make('project.index')->with($data);
But I don't know how I can "merge" the two codes?
I can also use :
$data = array(
'test2' => DB::table('martialp')
->orderBy('date', 'DESC')
->paginate(4)
);
But my class MyORM for exemple is useless with this previous code.
$data = MyORM::orderBy('date', 'DESC')->paginate(15);
return View::make('project.index', compact('data'));

Codeigniter Join messing up 'id' field

I have a codeigniter query to get a list of questions from my database. I'm using some joins to get the category name and the answer type. Its working good to output everything, but when i try and output the id of the row from the "questions" table, it displays as "2" which is the answer_type_id.
Maybe I'm doing this wrong, i'm fairly new to joins. Any help is appreciated:
function get_questions($category_id) {
$this->db->select('*');
$this->db->from('questions');
$this->db->where('category_id', $category_id);
$this->db->join('categories', 'questions.category_id = categories.id');
$this->db->join('answer_type', 'questions.answer_type_id = answer_type.id');
$this->db->order_by('priority', 'desc');
$query = $this->db->get();
$data = array();
foreach ($query->result() as $row) {
$data[] = array(
'id' => $row->id,
'category' => $row->category,
'type' => $row->type,
'question' => $row->question,
'answer' => $row->answer_type,
'priority' => $row->priority,
);
}
return $data;
}
Update===============
I have added "left" for my join type but the problem persists. The question id's should be 2 and 3. But when i print my array returned, they are both 2 (which is the answer_type_id).
Here is the updated code (only left join changed)...
function get_questions($category_id) {
$this->db->select('*');
$this->db->from('questions');
$this->db->where('category_id', $category_id);
$this->db->join('categories', 'questions.category_id = categories.id', 'left');
$this->db->join('answer_type', 'questions.answer_type_id = answer_type.id', 'left');
$this->db->order_by('priority', 'desc');
$query = $this->db->get();
$data = array();
foreach ($query->result() as $row) {
$data[] = array(
'id' => $row->id,
'category' => $row->category,
'type' => $row->type,
'question' => $row->question,
'answer' => $row->answer_type,
'priority' => $row->priority,
);
}
return $data;
}
And here is the output it returns:
Array (
[0] => Array (
[id] => 2
[category] => Herbs
[type] => 2
[question] => What Type of Vehicle do You own?
[answer] => Drop down list [priority] => 0
)
[1] => Array (
[id] => 2
[category] => Herbs
[type] => 3
[question] => What is Your Favorite Herb
[answer] => Drop down list [priority] => 0
)
)
The reason you are not getting the proper ids is you are selecting *.
Use aliases so that give them separate names and you will be access them
as you want like this.
function get_questions($category_id) {
$this->db->select('questions.*');
$this->db->select('answer_type.answer_type_id');
$this->db->select('answer_type.other_column');
$this->db->from('questions');
$this->db->where('category_id', $category_id);
$this->db->join('categories', 'questions.category_id = categories.id', 'left');
$this->db->join('answer_type', 'questions.answer_type_id = answer_type.id', 'left');
$this->db->order_by('priority', 'desc');
return $this->db->get()->result_array();
}
Also Codeigniter database class provide a method call result_array()
Which is already alternate of the loop you are using. So use it instead of
extra loop code.
Just change it to this:
'id' => $row->category_id
The problem is that the id column is ambiguous. In cases where your selecting columns across tables with columns that have the same name, you can also use the AS keyword to rename a column.
For example:
$this->db->select("questions.*, categories.id AS cat_id, answer_type.id AS ans_id");
By chance are you (maybe) only getting one row as a result, where all the ids match?
You should specify your join type, or be more specific in your query, so that you keep the question.id value.
For this question, you could specify the join as a left join, to keep all the data from questions table and tack on from categories and answer_types where its found.
see CodeIgniter ActiveRecord docs
The questions id needs to be defined as its own name. To pull ALL the data from the other tables, follow up with asterisks for the other tables, like so...
function get_questions($category_id) {
$this->db->select('questions.id as questions_id, questions.*, categories.*, answer_type.*');
$this->db->from('questions');
$this->db->where('category_id', $category_id);
$this->db->join('categories', 'questions.category_id = categories.id', 'left');
$this->db->join('answer_type', 'questions.answer_type_id = answer_type.id', 'left');
$this->db->order_by('priority', 'desc');
$query = $this->db->get();
$data = array();
foreach ($query->result() as $row) {
$data[] = array(
'id' => $row->questions_id,
'category' => $row->category,
'type' => $row->type,
'question' => $row->question,
'answer' => $row->answer_type,
'priority' => $row->priority,
);
}
return $data;
}
Use alias for your id columns like the above example.
...
$this->db->select("questions.*, categories.id AS cat_id, answer_type.id AS ans_id");
...
...
Now you get your data because only have one id column.
Here you have an article: http://chrissilich.com/blog/codeigniter-active-record-aliasing-column-names-to-prevent-overwriting-especially-columns-named-id/

Propel, Add alias to select statement

I'm using propel master-dev with symfony 2.1.
Is possible to write something like that ? Else how can I add an alias to the select statement.
$products = ProdottinewQuery::create()
->leftJoinWith('Prodotticolori')
->leftJoinWith('Alberocategorie')
->leftJoinWith('Brand')
->leftJoinWith('Prodottimateriali')
->leftJoinWith('Prodottigroffatura')
->select(array('id',
'codice',
'nomeEng',
'Alberocategorie.nomeeng' => 'category',
'Prodotticolori.coloreeng' => 'color',
'Brand.brand' => 'brand',
'Prodottimateriali.materialeeng' => 'material',
'Prodottigroffatura.groffaturaeng' => 'groffage'))
->orderById()
->limit($howmany)
->find();
Resolved:
$products = ProdottinewQuery::create()
->leftJoinWith('Prodotticolori')
->leftJoinWith('Alberocategorie')
->leftJoinWith('Brand')
->leftJoinWith('Prodottimateriali')
->leftJoinWith('Prodottigroffatura')
->select(array('id',
'codice',
'nomeEng'))
->withColumn('Alberocategorie.nomeeng', 'category')
->withColumn('Prodotticolori.coloreeng', 'color')
->withColumn('Brand.brand', 'brand')
->withColumn('Prodottimateriali.materialeeng', 'material')
->withColumn('Prodottigroffatura.groffaturaeng', 'groffage')
->orderById()
->limit($howmany)
->find();

Categories