<?php
include "../dcon.php";
$sql = "select * FROM posts left join comments on comments.Cpostid=posts.PostId left join likes on likes.postid=posts.PostId";
$query=mysqli_query($mysqli,$sql);
$result = mysqli_num_rows($query);
$menus=array();
for($i=0; $i<$result; $i++){
$row = mysqli_fetch_all($query,MYSQLI_ASSOC);
foreach($row as $index => $row ){
$menus[]=[
'PostId'=>$row['PostId'],
'PostVideo'=>$row['PostVideo'],
'PostDesc'=>$row['PostDesc'],
'PostImage'=>$row['PostImage'],
'PostedBy'=>$row['PostedBy'],
'UserName'=>$row['UserName'],
'Status'=>$row['Status'],
'PostParent'=>$row['PostParent'],
'likes'=>$row['likes'],
'comments'=>[
$index => [
'commentsid'=>$row['commentsId'],
'comments'=>$row['comments'],
'Cpostid'=>$row['Cpostid'],
'time'=>$row['time'],
],],
'likes'=>[
$index =>[
'Likeid'=>$row['Lid'],
'dislikes'=>$row['dislikes'],
'postid'=>$row['postid'],
'userid'=>$row['userid'],
]]
];
}
}
echo json_encode($menus,JSON_PRETTY_PRINT);
?>
**
this is my code i have three table posts table, comments table, and likes table. i have a left joined all three tables with postid common in all three tables. im getting all data perfectly but im getting repeating data of postdata (ex:Postid=1) i dont want that.
my problem is getting repeating data of Postdata(ex:Postid=1) i want to make a parent of Postdata where postsdata=1 and i want to insert all data into parent
**
[
{
"PostId": "1",
"PostVideo": "v2.mp4",
"PostDesc": "this is a tutorial on bench press",
"PostImage": "null",
"PostedBy": "Irfan khan",
"UserName": "irfan",
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
"comments": {
"commentsid": "1",
"comments": "awesome video",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
}
},
{
"PostId": "1",
"PostVideo": "v2.mp4",
"PostDesc": "this is a tutorial on bench press",
"PostImage": "null",
"PostedBy": "Irfan khan",
"UserName": "khan",
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
"comments": {
"commentsid": "2",
"comments": "good workouts",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
}
},
{
"PostId": "1",
"PostVideo": "v1.mp4",
"PostDesc": "Chicken generally includes low fat in the meat itself (castrated roosters excluded). The fat is highly concentrated on the skin. A 100g serving of baked chicken breast contains 4 grams of fat and 31 grams of protein, compared to 10 grams of fat and 27 grams of protein for the same portion of broiled, lean skirt steak.",
"PostImage": "im1",
"PostedBy": "Rehmat",
"UserName": null,
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "20",
"dislikes": "0",
"postid": "1",
"userid": "4"
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
},
{
"PostId": "1",
"PostVideo": "v1.mp4",
"PostDesc": "Chicken generally includes low fat in the meat itself (castrated roosters excluded). The fat is highly concentrated on the skin. A 100g serving of baked chicken breast contains 4 grams of fat and 31 grams of protein, compared to 10 grams of fat and 27 grams of protein for the same portion of broiled, lean skirt steak.",
"PostImage": "im1",
"PostedBy": "Rehmat",
"UserName": null,
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "26",
"dislikes": "0",
"postid": "1",
"userid": "4"
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
},
{
"PostId": "3",
"PostVideo": null,
"PostDesc": "this is an image of chicken",
"PostImage": "post.jpg",
"PostedBy": "khan",
"UserName": null,
"Status": "0",
"PostParent": null,
"likes": {
"Likeid": null,
"dislikes": null,
"postid": null,
"userid": null
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
},
{
"PostId": "9",
"PostVideo": null,
"PostDesc": "gdhgh",
"PostImage": "ghghdf",
"PostedBy": null,
"UserName": null,
"Status": null,
"PostParent": null,
"likes": {
"Likeid": null,
"dislikes": null,
"postid": null,
"userid": null
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
}
];
Related
I have php laravel framework project (laravel-8) and at DB , I have column which has array of objects like this:
[
{
"id": "G0",
"name": "Social-Emotional Understanding",
"questions": [
{
"gId": "G0",
"id": 1,
"question_id": 34,
"question_title": "Age - appropriate social- emotional understanding. Clearly understands facial expressions, gestures, tone of voice, and body language of\r\nothers. Able to under - stand that others may have a different perspective and what that perspective may be.",
"question_note": null,
"answers": [
{
"answer_index": "1",
"answer_text": "yes",
"answer_image": null,
"answers_redirection_group_index": "G1",
"answers_redirection_group_question": "noQuestion",
"degree": "1"
},
{
"answer_index": "2",
"answer_text": "No",
"answer_image": null,
"answers_redirection_group_index": "noGroup",
"answers_redirection_group_question": "noQuestion",
"degree": 0
},
{
"answer_index": "3",
"answer_text": "N/A",
"answer_image": null,
"answers_redirection_group_index": "noGroup",
"answers_redirection_group_question": "noQuestion",
"degree": 0
}
]
},
{
"gId": "G0",
"id": 2,
"question_id": 35,
"question_title": "Mildly impaired social-emotional understanding. Responsive to most facial expressions and expressions of emotion in others’ gestures and\r\nbody language, but these cues may need to be slightly exaggerated. Subtler expressions such as mild sarcasm, doubt, or ambiguity are\r\nsometimes not understood. The ability to take another’s perspective is inconsistent.",
"question_note": null,
"answers": [
{
"answer_index": "1",
"answer_text": "yes",
"answer_image": null,
"answers_redirection_group_index": "G1",
"answers_redirection_group_question": "noQuestion",
"degree": "2"
},
{
"answer_index": "2",
"answer_text": "No",
"answer_image": null,
"answers_redirection_group_index": "noGroup",
"answers_redirection_group_question": "noQuestion",
"degree": 0
},
{
"answer_index": "3",
"answer_text": "N/A",
"answer_image": null,
"answers_redirection_group_index": "G1",
"answers_redirection_group_question": "noQuestion",
"degree": "1.5"
}
]
},
{
"gId": "G0",
"id": 3,
"question_id": 36,
"question_title": "Moderately impaired social - emotional understanding. Shows an under - standing of facial expressions, tone of voice, and body language\r\nonly when these cues are exaggerated. Is likely to ignore or misunderstand or perspective of others.",
"question_note": null,
"answers": [
{
"answer_index": "1",
"answer_text": "yes",
"answer_image": null,
"answers_redirection_group_index": "G1",
"answers_redirection_group_question": "noQuestion",
"degree": "3"
},
{
"answer_index": "2",
"answer_text": "No",
"answer_image": null,
"answers_redirection_group_index": "noGroup",
"answers_redirection_group_question": "noQuestion",
"degree": 0
},
{
"answer_index": "3",
"answer_text": "N/A",
"answer_image": null,
"answers_redirection_group_index": "G1",
"answers_redirection_group_question": "noQuestion",
"degree": "2.5"
}
]
}
]
},
{
"id": "G1",
"name": "Emotional expression and regulation of emotions",
"questions": [
{
"gId": "G1",
"id": 3,
"question_id": 104,
"question_title": "Moderately abnormal emotional response. Expression of emotions is flat, excessive, or frequently inconsistent with situation or content\r\nof verbalized topic. May display greater emotion than expected about special interest or idiocy necrotic concerns. Ability to describe or\r\nunderstand emotional states in self is limited. Serious problems with emotional regulation that occur frequently in at least one setting.",
"question_note": null,
"answers": [
{
"answer_index": "1",
"answer_text": "Yes",
"answer_image": null,
"answers_redirection_group_index": "G2",
"answers_redirection_group_question": "noQuestion",
"degree": "3"
},
{
"answer_index": "2",
"answer_text": "No",
"answer_image": null,
"answers_redirection_group_index": "noGroup",
"answers_redirection_group_question": "noQuestion",
"degree": 0
},
{
"answer_index": "3",
"answer_text": "N/A",
"answer_image": null,
"answers_redirection_group_index": "G2",
"answers_redirection_group_question": "noQuestion",
"degree": "2.5"
}
]
},
{
"gId": "G1",
"id": 2,
"question_id": 103,
"question_title": "Mildly abnormal emotional response. Emotional expressions are relatively flat, distorted, or slightly exaggerated. Nonverbal expression of\r\nemotions does not always match verbal content. Able to describe several emotions in self but limited compared to developmental level.\r\nMay have intermittent emotional regulation problems.",
"question_note": null,
"answers": [
{
"answer_index": "1",
"answer_text": "Yes",
"answer_image": null,
"answers_redirection_group_index": "G2",
"answers_redirection_group_question": "noQuestion",
"degree": "2"
},
{
"answer_index": "2",
"answer_text": "No",
"answer_image": null,
"answers_redirection_group_index": "noGroup",
"answers_redirection_group_question": "noQuestion",
"degree": 0
},
{
"answer_index": "3",
"answer_text": "N/A",
"answer_image": null,
"answers_redirection_group_index": "G2",
"answers_redirection_group_question": "noQuestion",
"degree": "1.5"
}
]
}
]
}
]
How can I create array from all "question_id" ? so I can return this questions from question table by using " whereIn('id', $ids)->get(); "
so the neede array must be like $ids = [34,35,36,104,103] so I will use this array to get this questions from question table
This is my code I have three table posts table, comments table, and likes table. I have a left joined all three tables with postid common in all three tables. I'm getting all data perfectly but I'm getting repeating data of postdata (ex: Postid=1) I don't want that. My problem is getting repeating data of Postdata (ex: Postid=1) I want to make a parent of Postdata where postsdata=1 and I want to insert all data into parent
<?php
include "../dcon.php";
$sql = "select * FROM posts left join comments on comments.Cpostid=posts.PostId left join likes on likes.postid=posts.PostId";
$query=mysqli_query($mysqli,$sql);
$result = mysqli_num_rows($query);
$menus=array();
for($i=0; $i<$result; $i++){
$row = mysqli_fetch_all($query,MYSQLI_ASSOC);
foreach($row as $index => $row ){
$menus[]=[
'PostId'=>$row['PostId'],
'PostVideo'=>$row['PostVideo'],
'PostDesc'=>$row['PostDesc'],
'PostImage'=>$row['PostImage'],
'PostedBy'=>$row['PostedBy'],
'UserName'=>$row['UserName'],
'Status'=>$row['Status'],
'PostParent'=>$row['PostParent'],
'likes'=>$row['likes'],
'comments'=>[
$index => [
'commentsid'=>$row['commentsId'],
'comments'=>$row['comments'],
'Cpostid'=>$row['Cpostid'],
'time'=>$row['time'],
],],
'likes'=>[
$index =>[
'Likeid'=>$row['Lid'],
'dislikes'=>$row['dislikes'],
'postid'=>$row['postid'],
'userid'=>$row['userid'],
]]
];
}
}
echo json_encode($menus,JSON_PRETTY_PRINT);
?>
My output was below:
[
{
"PostId": "1",
"PostVideo": "v2.mp4",
"PostDesc": "this is a tutorial on bench press",
"PostImage": "null",
"PostedBy": "Irfan khan",
"UserName": "irfan",
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
"comments": {
"commentsid": "1",
"comments": "awesome video",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
}
},
{
"PostId": "1",
"PostVideo": "v2.mp4",
"PostDesc": "this is a tutorial on bench press",
"PostImage": "null",
"PostedBy": "Irfan khan",
"UserName": "khan",
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
"comments": {
"commentsid": "2",
"comments": "good workouts",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
}
},
{
"PostId": "1",
"PostVideo": "v1.mp4",
"PostDesc": "Chicken generally includes low fat in the meat itself (castrated roosters excluded). The fat is highly concentrated on the skin. A 100g serving of baked chicken breast contains 4 grams of fat and 31 grams of protein, compared to 10 grams of fat and 27 grams of protein for the same portion of broiled, lean skirt steak.",
"PostImage": "im1",
"PostedBy": "Rehmat",
"UserName": null,
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "20",
"dislikes": "0",
"postid": "1",
"userid": "4"
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
},
{
"PostId": "1",
"PostVideo": "v1.mp4",
"PostDesc": "Chicken generally includes low fat in the meat itself (castrated roosters excluded). The fat is highly concentrated on the skin. A 100g serving of baked chicken breast contains 4 grams of fat and 31 grams of protein, compared to 10 grams of fat and 27 grams of protein for the same portion of broiled, lean skirt steak.",
"PostImage": "im1",
"PostedBy": "Rehmat",
"UserName": null,
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "26",
"dislikes": "0",
"postid": "1",
"userid": "4"
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
},
{
"PostId": "3",
"PostVideo": null,
"PostDesc": "this is an image of chicken",
"PostImage": "post.jpg",
"PostedBy": "khan",
"UserName": null,
"Status": "0",
"PostParent": null,
"likes": {
"Likeid": null,
"dislikes": null,
"postid": null,
"userid": null
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
},
{
"PostId": "9",
"PostVideo": null,
"PostDesc": "gdhgh",
"PostImage": "ghghdf",
"PostedBy": null,
"UserName": null,
"Status": null,
"PostParent": null,
"likes": {
"Likeid": null,
"dislikes": null,
"postid": null,
"userid": null
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
}
];
I want my output like below:
{
"PostId": "1",
"PostVideo": "v2.mp4",
"PostDesc": "this is a tutorial on bench press",
"PostImage": "null",
"PostedBy": "Irfan khan",
"UserName": "irfan",
"Status": "1",
"PostParent": null,
"likes":
'0':{
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
'1':{
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
'2':{
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
'3':{
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
"comments":
'0':{
"commentsid": "1",
"comments": "awesome video",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
},
'1':{
"commentsid": "1",
"comments": "awesome video",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
},
'2':{
"commentsid": "1",
"comments": "awesome video",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
},
'3':{
"commentsid": "1",
"comments": "awesome video",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
}
},
{
"PostId": "9",
"PostVideo": null,
"PostDesc": "gdhgh",
"PostImage": "ghghdf",
"PostedBy": null,
"UserName": null,
"Status": null,
"PostParent": null,
"likes": {
"Likeid": null,
"dislikes": null,
"postid": null,
"userid": null
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
}
Hmm... At first I thought that your loops were the problem, and you misunderstood the behavior. But then I saw your "i want my output like below", and that didn't made sense, specifically you wanting duplicate likes/comments.
First, the loops: a for loop and an inner foreach loop. The for loop iterates over the number of results. The inner foreach loop iterates over all the results. So if we have 6 results, instead of only iterating 6 times, we iterate 36 times (6 result count x 6 results).
We actually need only 1 loop:
$query = mysqli_query($mysqli, $sql);
$menus = [];
$rows = mysqli_fetch_all($query, MYSQLI_ASSOC);
foreach ($rows as $index => $row) {
$menus[] = [
...
];
}
Next, we avoid duplicate posts by indexing the $menus with PostId. If the PostId does not yet exist in $menus, we insert the post; otherwise we just append the like/comment:
$query = mysqli_query($mysqli, $sql);
$menus = [];
$rows = mysqli_fetch_all($query, MYSQLI_ASSOC);
foreach ($rows as $row) {
if (!isset($menus[$row['PostId']])) {
$menus[$row['PostId']] = [
'PostId' => $row['PostId'],
...
'comments' => [],
'likes' => [],
];
}
$menus[$row['PostId']]['comments'][] = [
...
];
$menus[$row['PostId']]['likes'][] = [
...
];
}
If for some reason you don't want the $menus indexed by PostId, we can just call array_values() after the loop to re-index it with zero-based sequential integer:
foreach (...) { ... }
$menus = array_values($menus);
As for the duplicate likes/comments, you were explicit about it. But just in case you actually want non-duplicate, we can also index them by their Likeid and commentsid, and insert/ignore as necessary:
$query = mysqli_query($mysqli, $sql);
$menus = [];
$rows = mysqli_fetch_all($query, MYSQLI_ASSOC);
foreach ($rows as $row) {
if (!isset($menus[$row['PostId']])) {
$menus[$row['PostId']] = [
'PostId' => $row['PostId'],
...
'comments' => [],
'likes' => [],
];
}
if (!isset($menus[$row['PostId']]['comments'][$row['commentsid']])) {
$menus[$row['PostId']]['comments'][$row['commentsid']] = [
...
];
}
if (!isset($menus[$row['PostId']]['Likes'][$row['Lid']])) {
$menus[$row['PostId']]['Likes'][$row['Lid']] = [
...
];
}
}
And if we also don't want the comments/likes indexed by commentsid/Lid, we can call array_values() on them as well:
foreach (...) { ... }
$menus = array_values($menus);
foreach ($menus as &$menu) {
$menu['comments'] = array_values($menu['comments']);
$menu['likes'] = array_values($menu['likes']);
}
unset($menu);
// Or
array_walk($menus, function (&$menu) {
$menu['comments'] = array_values($menu['comments']);
$menu['likes'] = array_values($menu['likes']);
});
CakePHP Rest-API pagination in an array of array. Like, containable model pagination in CakePHP for reducing API load.
Some existing code :
$this->request->data['page'];
$data = $this->Model1->find('all',array(
'contain' => array('Model2'),
'fields' => array(),
'conditions' => array('Model1.status' => 1 )
));
Below API response and I want to paginate in ProductUser array because when lots of product load at one-time app will be hang. It's possible or any other way to reduce data load in CakePHP.
API Response :
"status": true,
"message": "Available devices!",
"data": [
{
"id": "6",
"name": "Television",
"parent_id": "0",
"image": "",
"status": "1",
"created": "2019-06-10 15:22:44",
"modified": "2019-06-10 15:22:44",
"ProductUser": [ //Paginate this array
{
"id": "1",
"user_id": "17",
"category_id": "6",
"brand_id": "1",
"product_id": "17",
"date_of_purchase": "2019-06-22",
"seller_id": "1",
"warranty_year": "0",
"warranty_month": "0",
"warranty_end_date": null,
"purchese_price": null,
"bill_upload": "",
"emi_year": "0",
"emi_month": "0",
"emi_start_date": null,
"emi_end_date": null,
"insurance_company_id": "0",
"insurance_year": "0",
"insurance_month": "0",
"insurance_end_date": null,
"created": "2019-06-22 14:13:01",
"modified": "2019-06-22 14:17:07",
"Product": {
"id": "17",
"category_id": "6",
"brand_id": "1",
"product_code": "Samsung LED TV 39 inch",
"name": "Samsung LED TV 39 inch",
"selling_price": "13000",
"short_description": "Television",
"image": "catalog\/sam39.jpg",
"status": "1",
"created": "2019-05-14 00:00:00",
"modified": "2019-05-14 00:00:00"
}
},
{
"id": "1",
"user_id": "17",
"category_id": "6",
"brand_id": "1",
"product_id": "17",
"date_of_purchase": "2019-06-22",
"seller_id": "1",
"warranty_year": "0",
"warranty_month": "0",
"warranty_end_date": null,
"purchese_price": null,
"bill_upload": "",
"emi_year": "0",
"emi_month": "0",
"emi_start_date": null,
"emi_end_date": null,
"insurance_company_id": "0",
"insurance_year": "0",
"insurance_month": "0",
"insurance_end_date": null,
"created": "2019-06-22 14:13:01",
"modified": "2019-06-22 14:17:07",
"Product": {
"id": "17",
"category_id": "6",
"brand_id": "1",
"product_code": "Samsung LED TV 39 inch",
"name": "Samsung LED TV 39 inch",
"selling_price": "13000",
"short_description": "Television",
"image": "catalog\/sam39.jpg",
"status": "1",
"created": "2019-05-14 00:00:00",
"modified": "2019-05-14 00:00:00"
}
}
]
}]
I have executed the following code. The wierd thing is that fields like id_expediente and id_juzgado are defined as integers on my mysql database and for any reason json_encode($respuesta) is returning those fields as Strings.
I want to keep its data types(as were defined in mysql)
$sql = $this->con->prepare($consulta);
$ok = $sql->execute(array());
$query = $sql->fetchAll(PDO::FETCH_ASSOC);
$respuesta = array (
"codigo"=>1001,
"mensaje"=>$mensajes[1001],
"contenido"=>$query
);
return json_encode($respuesta);
What json_encode($respuesta) shows:
{
"codigo": 1001,
"mensaje": "",
"contenido": [
{
"id_expediente": "11",
"id_juzgado": "3",
"nombre": "PEDRO",
"apellido1": "SANTIAGO",
"apellido2": "FERNANDEZ",
"fecha_defuncion": "2014-11-11 12:45:34",
"id_tipo_zona": "4",
"fallecio_en": "DOMICILIO - EL BURGOS",
"id_tipo_servicio": "1",
"enterramiento": "EL BURGO",
"empresa_id": "0",
"compania": "ALMUDENA",
"responsable": "SENSI MADRID",
"responsable_tlf": "600102000",
"creado_en": "2015-09-08 12:06:54",
"actualizado_en": "2015-09-08 12:06:54",
"id": "15",
"id_empleado": "1",
"estados_expediente": "1"
},
{
"id_expediente": "345",
"id_juzgado": "1",
"nombre": "Juan",
"apellido1": "Bartolome",
"apellido2": null,
"fecha_defuncion": "2015-09-08 12:06:54",
"id_tipo_zona": "1",
"fallecio_en": null,
"id_tipo_servicio": "1",
"enterramiento": "Malaga",
"empresa_id": "2",
"compania": null,
"responsable": null,
"responsable_tlf": "666777888",
"creado_en": "2015-09-30 21:13:07",
"actualizado_en": "2015-09-30 21:13:07",
"id": "31",
"id_empleado": null,
"estados_expediente": "1"
},
{
"id_expediente": "350",
"id_juzgado": "1",
"nombre": "Juan",
"apellido1": "Bartolome",
"apellido2": null,
"fecha_defuncion": "2015-09-08 12:06:54",
"id_tipo_zona": "1",
"fallecio_en": null,
"id_tipo_servicio": "1",
"enterramiento": "Malaga",
"empresa_id": "2",
"compania": null,
"responsable": null,
"responsable_tlf": "666777888",
"creado_en": "2015-09-30 21:13:15",
"actualizado_en": "2015-09-30 21:13:15",
"id": "32",
"id_empleado": null,
"estados_expediente": "1"
},
{
"id_expediente": "355",
"id_juzgado": "1",
"nombre": "Jorge",
"apellido1": "Bartolome",
"apellido2": null,
"fecha_defuncion": "2015-09-08 12:06:54",
"id_tipo_zona": "1",
"fallecio_en": null,
"id_tipo_servicio": "1",
"enterramiento": "Malaga",
"empresa_id": "2",
"compania": null,
"responsable": null,
"responsable_tlf": "666777888",
"creado_en": "2015-09-30 21:13:31",
"actualizado_en": "2015-09-30 21:13:31",
"id": "33",
"id_empleado": null,
"estados_expediente": "1"
},
{
"id_expediente": "400",
"id_juzgado": "1",
"nombre": "Javier",
"apellido1": "Bartolome",
"apellido2": "Bengochea",
"fecha_defuncion": "2015-09-08 12:06:54",
"id_tipo_zona": "1",
"fallecio_en": null,
"id_tipo_servicio": "1",
"enterramiento": "Malaga",
"empresa_id": "2",
"compania": null,
"responsable": null,
"responsable_tlf": "666777888",
"creado_en": "2015-09-30 21:15:39",
"actualizado_en": "2015-09-30 21:15:39",
"id": "34",
"id_empleado": null,
"estados_expediente": "1"
}
]
}
I am running the following query in my laravel code,
$organisations = Organisation::with('projects', 'projects.clients')
->with('clients')
->get();
$organisations->load('users');
This is loading in my organisations table, and should in thoery load in any related models as well so I would expect an object that looks like this to be returned,
organisation {
projects {
clients {
}
}
users {
}
}
Basically an organisation can have many projects, a project can have one client, an organisation can also have many users and many clients.
What I am wanting from my query is for the client data to returned with each project but I am not getting that, currently I am getting the following object returned.
[
{
"id": "114",
"name": "XXXXXXX",
"slug": "XXXXXXX",
"information": "",
"type": "organisation",
"notifications": "0",
"add_all": "0",
"created_at": "2014-12-16 10:16:03",
"updated_at": "2014-12-16 10:16:03",
"clients": [
{
"id": "39",
"name": "Simon's Test",
"information": "",
"address": null,
"website": null,
"email": null,
"phone": null,
"type": "client",
"add_all": "0",
"created_at": "2014-12-16 10:16:20",
"updated_at": "2014-12-16 10:16:20",
"user_id": "1",
"owner_id": "114",
"projects": [
{
"id": "56",
"name": "iOS Application",
"description": "An iOS application that will be available on iPhone and iPad. Something that will change the way we manage projects.",
"total_cost": "5000.00",
"start_date": "2014-01-01",
"finish_date": "2014-12-10",
"status": "1",
"sales_person": null,
"project_manager": null,
"client_id": "39",
"organisation_id": "114",
"owner_id": "114",
"user_id": "1",
"created_at": null,
"updated_at": "2014-12-15 13:20:07"
},
{
"id": "57",
"name": "Android Application",
"description": "An android application that will run on any android phone, upto a certain version.",
"total_cost": "6500.00",
"start_date": "2015-01-31",
"finish_date": "2015-03-19",
"status": "2",
"sales_person": null,
"project_manager": null,
"client_id": "39",
"organisation_id": "114",
"owner_id": "114",
"user_id": "1",
"created_at": null,
"updated_at": "2014-12-11 15:01:15"
},
{
"id": "58",
"name": "Java Application",
"description": "A windows phone application, to be released for the small market share that market has.",
"total_cost": "7500.00",
"start_date": "2014-12-12",
"finish_date": "2014-12-31",
"status": "3",
"sales_person": null,
"project_manager": null,
"client_id": "39",
"organisation_id": "114",
"owner_id": "114",
"user_id": "1",
"created_at": null,
"updated_at": "2014-12-11 15:01:15"
},
{
"id": "59",
"name": "OSX Application Beta",
"description": "A desktop application for the Mac. More feature rich than the native iOS apps, more like the web application for desktop.",
"total_cost": "20000.00",
"start_date": "2014-11-20",
"finish_date": "2014-12-19",
"status": "2",
"sales_person": null,
"project_manager": null,
"client_id": "39",
"organisation_id": "114",
"owner_id": "114",
"user_id": "1",
"created_at": null,
"updated_at": "2014-11-28 16:01:41"
}
],
"users": []
}
],
"projects": [
{
"id": "56",
"name": "iOS Application",
"description": "An iOS application that will be available on iPhone and iPad. Something that will change the way we manage projects.",
"total_cost": "5000.00",
"start_date": "2014-01-01",
"finish_date": "2014-12-10",
"status": "1",
"sales_person": null,
"project_manager": null,
"client_id": "39",
"organisation_id": "114",
"owner_id": "114",
"user_id": "1",
"created_at": null,
"updated_at": "2014-12-15 13:20:07",
"pivot": {
"organisation_id": "114",
"project_id": "56"
}
},
{
"id": "57",
"name": "Android Application",
"description": "An android application that will run on any android phone, upto a certain version.",
"total_cost": "6500.00",
"start_date": "2015-01-31",
"finish_date": "2015-03-19",
"status": "2",
"sales_person": null,
"project_manager": null,
"client_id": "39",
"organisation_id": "114",
"owner_id": "114",
"user_id": "1",
"created_at": null,
"updated_at": "2014-12-11 15:01:15",
"pivot": {
"organisation_id": "114",
"project_id": "57"
}
},
{
"id": "58",
"name": "Java Application",
"description": "A windows phone application, to be released for the small market share that market has.",
"total_cost": "7500.00",
"start_date": "2014-12-12",
"finish_date": "2014-12-31",
"status": "3",
"sales_person": null,
"project_manager": null,
"client_id": "39",
"organisation_id": "114",
"owner_id": "114",
"user_id": "1",
"created_at": null,
"updated_at": "2014-12-11 15:01:15",
"pivot": {
"organisation_id": "114",
"project_id": "58"
}
},
{
"id": "59",
"name": "OSX Application Beta",
"description": "A desktop application for the Mac. More feature rich than the native iOS apps, more like the web application for desktop.",
"total_cost": "20000.00",
"start_date": "2014-11-20",
"finish_date": "2014-12-19",
"status": "2",
"sales_person": null,
"project_manager": null,
"client_id": "39",
"organisation_id": "114",
"owner_id": "114",
"user_id": "1",
"created_at": null,
"updated_at": "2014-11-28 16:01:41",
"pivot": {
"organisation_id": "114",
"project_id": "59"
}
}
],
"users": [
{
"id": "1",
"email": "simon#pikcells.com",
"first_name": "Simon",
"last_name": "Ainley",
"display_name": "simonainley",
"initials": "SA",
"remember_me": null,
"active": "1",
"invite_code": null,
"forgotten_code": null,
"login_type": "normal",
"api_token": null,
"created_at": "-0001-11-30 00:00:00",
"updated_at": "2014-12-12 11:53:53",
"deleted_at": null,
"pivot": {
"organisation_id": "114",
"user_id": "1",
"is_admin": "1"
}
}
]
}
]
In the object above you can see that I get the organisations projects and clients returned to me, but the clients have nested projects, i.e what projects they are related too, but I would like to return projects nested with the clients they are related too is this possible?
One note about the naming. If your projects can only have one client the relationship would better off if called "client" instead of "clients".
Project Model
//Client relationship in Project model
client()
{
$this->belongsTo('Client')
}
this way is more readable and you can call it like this
Organisation::with('projects.client', 'clients', 'users')->get()
you need the relationships projects, clients and users in the Organisation model.
Check the Eloquent documentation for more info about relationships
$organisations = Organisation::with(array('Projects'=>function($q){
$q->with('Client')
},'Clients','Users'))->get()
You can fetch expected output using above code
You have to define 3 relationships in Organization model : Projects,Clients,Users
You have to define 1 relationship in Project model : Client