This is my first ever Laravel project, please bear with us. I am trying to display a parent->child hierarchy (not recursive), something akin to below:
Category 1
----List item
----------Resource 1
----List item
----------Resource 2
Category 2
-----List item 1
-----List item 2....etc
I can't get my head around how to write the query to get the resources linked to the subStatement, not the top category, basically, an inner join related to SubStatement. It is currently displayed as so;
{
"id": 1,
"name": "Category 1: Practising plumbing overview",
"description": "<p>Category 1: Practising plumbing overview</p>",
"created_at": "2022-01-06 15:48:49",
"updated_at": "2022-01-06 15:48:49",
"deleted_at": null,
"plumbing_area_id": 1,
"category_id": 1,
"SubStatement": [
{
"id": 1,
"title": "Plying narrative for Category 1",
"description": "<p>Body of content.</p>",
"theme_id": 1,
"plumbing_area_id": 1
},
{
"id": 2,
"title": "Lay narrative for Category 1",
"description": "<p>body description.</p>",
"theme_id": 1,
"plumbing_area_id": 1
}
],
"resources": []
},
{
"id": 2,
"name": "Category 2: AAV Practising plumbing introduction",
"description": "<p><strong>Category 2:</strong> AAV Practising plumbing introduction</p>",
"created_at": "2022-01-06 15:49:12",
"updated_at": "2022-01-06 15:49:12",
"deleted_at": null,
"plumbing_area_id": 1,
"category_id": 1,
"SubStatement": [
{
"id": 3,
"title": "Plying narrative for Category 2",
"description": "<p>Body of content;</p>",
"theme_id": 2,
"plumbing_area_id": 1
},
{
"id": 4,
"title": "Lay narrative for Category 2",
"description": "<p>Body of content</p>",
"theme_id": 2,
"plumbing_area_id": 1
}
],
"resources": []
},
{
"id": 3,
"name": "Category 3: AAV Practising plumbing design",
"description": "<p><strong>Category 3: </strong>AAV Practising plumbing design</p>",
"created_at": "2022-01-06 15:49:47",
"updated_at": "2022-01-06 15:49:47",
"deleted_at": null,
"plumbing_area_id": 1,
"category_id": 1,
"SubStatement": [
{
"id": 5,
"title": "Plying narrative for Category 3",
"description": "<p>Body of content;</p>",
"theme_id": 3,
"plumbing_area_id": 1
},
{
"id": 6,
"title": "Lay narrative for Category 3",
"description": “Blah blah</p>",
"theme_id": 3,
"plumbing_area_id": 1
}
],
"resources": []
},
{
"id": 4,
"name": "Category 4: another “category,
"description": “Body</p>",
"created_at": "2022-01-06 15:50:04",
"updated_at": "2022-01-06 15:50:04",
"deleted_at": null,
"plumbing_area_id": 1,
"category_id": 1,
"SubStatement": [
{
"id": 7,
"title": "Plying narrative for Category 4",
"description": "<p>sdfsdfsdf;</p>",
"theme_id": 4,
"plumbing_area_id": 1
},
{
"id": 8,
"title": "Lay narrative for Category 4",
"description": "<p> sdfsdfsdfsdf</p>",
"theme_id": 4,
"plumbing_area_id": 1
}
],
"resources": []
},
]
I am looking for something like below instead, please note where the resource node is:
[
{
"id": 1,
"name": "Category 1: Practising plumbing overview",
"description": "<p>Category 1: Practising plumbing overview</p>",
"created_at": "2022-01-06 15:48:49",
"updated_at": "2022-01-06 15:48:49",
"deleted_at": null,
"plumbing_area_id": 1,
"category_id": 1,
"SubStatement": [
{
"id": 1,
"title": "Plying narrative for Category 1",
"description": "<p>Body of content.</p>",
"theme_id": 1,
"plumbing_area_id": 1,
"resources": [
{
"id": 1,
"resource_title": "The name of the resource"
}
]
}
]
}
]
//Themes Model
{
return $this->hasMany(Statement::class, 'theme_id', 'id');
}
public function resources()
{
return $this->belongsToMany(Resource::class);
}
//the Controller below is outputting the the JSON above
{
$output = Theme::where ( 'category_id', '=', $category_id )
->with(['subStatement' =>
fn ($query) =>
$query->select('id','title','description','theme_id','therapy_area_id')
])
->with(['resources' =>
fn ($query) =>
$query->select('id','temporary_url')])
->get();
}
// I attempted writing something like this. It threw a "Integrity constraint violation: 1052 Column 'id' in field list is ambiguous" error
{
return $this->hasOneThrough(Statement::class, Resource::class);
}
Your main issue is that you need to nest the query.
I will first adding the relationships to your models according to your schema.
Then, I will add the base query for the nesting if I understood what you're trying to achieve correctly.
Models
Theme.php
public function subStatements()
{
return $this->hasMany(Statement::class); // 1-N
}
public function statements()
{
return $this->belongsToMany(Statement::class); // N-N
}
public function resources
{
return $this->belongsToMany(Resource::class); // N-N
}
Statement.php
public function theme()
{
return $this->belongsTo(Theme::class); // 1-N
}
public function themes()
{
return $this->belongsToMany(Theme::class); // N-N
}
public function resources
{
return $this->belongsToMany(Resource::class); // N-N
}
Resource.php
public function themes()
{
return $this->belongsToMany(Theme::class); // N-N
}
public function statements()
{
return $this->belongsToMany(Statement::class); // N-N
}
Query
$themes = Theme::query()
->where('category_id', $category_id)
->with([
'subStatements' => fn ($query) => $query->with('resources')
])
->get();
Related
This link Laravel filter one to many relationship has a solution related to my question but I don't know why the solutions are not working for me.
I am currently selecting all the offtaker sites and the apartments the site have but I want to filter the apartment to only apartment that the apartment id is equal to the offtakers apartment_id
Below are my model setup
offtaker model
public function sites(){
return $this->belongsTo(Sites::class,'site_id','id')->select('id','name');
}
site model
public function apartment(){
return $this->hasMany(Apartment::class,'site_id','id');
}
offtaker controller
return Offtakers::select(['id','site_id','offtaker_id','company_id','apartment_id'])
->with('sites',
)->with('sites.apartment',function($query){
$query->where(function($query){
$query->whereRaw("id = (select apartment_id from offtakers where apartment_id=apartments.id)");
});
})->get();
Current out put
{
"id": 2,
"site_id": "1",
"offtaker_id": 6,
"apartment_id": "8",
"sites": {
"id": 1,
"name": "first site",
"apartment": [
{
"id": 8,
"company_id": 1,
"site_id": 1,
"project_id": null,
"apartment_name": "apartment five",
"apartment_description": "test descriptions",
"amount": 8000
},
{
"id": 55,
"company_id": 1,
"site_id": 1,
"project_id": null,
"apartment_name": "apartment eleven",
"apartment_description": "test descriptions",
"amount": 550000
}
]
}
},
Expected out put
{
"id": 2,
"site_id": "1",
"offtaker_id": 6,
"apartment_id": "8",
"sites": {
"id": 1,
"name": "first site",
"apartment": [
{
"id": 8,
"company_id": 1,
"site_id": 1,
"project_id": null,
"apartment_name": "apartment five",
"apartment_description": "test descriptions",
"amount": 8000
},
]
}
},
For you, I suggest you add this package https://github.com/staudenmeir/eloquent-has-many-deep.
This will solve the 2 deep relationships Offtaker - Site - Apartment
Add new relationship in Offtaker model
public function apartments()
{
return $this->hasManyThrough(Apartment::class, Site::class);
}
And to use it:
return Offtaker::select(['id','site_id','offtaker_id','company_id','apartment_id'])
->with([
'sites' => function ($q) {
$q->where('id', 'offtakers.site_id');
},
'apartments' => function ($q) {
$q
->where('site_id', 'offtakers.site_id')
->where('apartment_id', 'offtakers.apartment_id');
}
])
->get();
However the result might a bit different that want you want
{
"id": 2,
"site_id": 1,
"offtaker_id": 6,
"apartment_id": 8,
"sites": [
{
"id": 1,
"name": "first site",
}
],
"apartments": [
{
"id": 8,
"company_id": 1,
"site_id": 1,
"project_id": null,
"apartment_name": "apartment five",
"apartment_description": "test descriptions",
"amount": 8000
}
]
},
....
I hope this can help you out.
I have 3 relational tables Cart, CartProducts and Products and in the query I have the low JSON result, but I want to add the product name and description information in cart_products.
Relationships:
Cart with CartProduct
public function cartProducts()
{
return $this->hasMany(CartProduct::class);
}
CartProduct with Product:
public function products()
{
return $this->belongsTo(Product::class);
}
And the query:
$data = Cart::with(['cartProducts'])->where('user_id', '=', $id)->orderBy('id')->get();
[
{
"id": 1,
"user_id": 4,
"amount": 55,
"cart_products": [
{
"id": 1,
"cart_id": 1,
"product_id": 6,
"price": 7.8,
"quantity": 1
},
{
"id": 3,
"cart_id": 1,
"product_id": 5,
"price": 66,
"quantity": 5
}
]
}
]
and this is the result I want
[
{
"id": 1,
"user_id": 4,
"amount": 55,
"cart_products": [
{
"id": 1,
"cart_id": 1,
"product_id": 6,
"name": "Product a"
"price": 7.8,
"quantity": 1
},
{
"id": 3,
"cart_id": 1,
"product_id": 5,
"name": "Product b"
"price": 66,
"quantity": 5
}
}
]
Tables
Cart: id|user_id|amount
--------------------------------------------------
CartProduct: id|cart_id|product_id|price|quantity
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/QDSRb.png
You can simply add an accessor and append it to your CartProduct model.
class CartProduct
{
protected $appends=[
'product_name'
];
public function getProductNameAttribute()
{
return $this->product->name;
}
}
I have categories with id, parent_id, slug , pivot table category_language which columns are id,category_id,language_id,value
As you can see I can translate parent category, but can't send desired $lang_id to children translations, so each children having all translations
here is what I get:
{
"id": 1,
"parent_id": 0,
"slug": "personal-computers",
"created_at": "2019-12-27 15:05:31",
"updated_at": "2019-12-27 15:05:31",
"children": [
{
"id": 3,
"parent_id": 1,
"slug": "accessories-for-pc",
"created_at": "2019-12-27 15:05:32",
"updated_at": "2019-12-27 15:05:32",
"translations": [
{
"id": 1,
"code": "en",
"name": "English",
"pivot": {
"category_id": 3,
"language_id": 1,
"value": "Acc for PC",
"id": 7
}
},
{
"id": 2,
"code": "ru",
"name": "Русский",
"pivot": {
"category_id": 3,
"language_id": 2,
"value": "Аксессуары для ноутбуков и ПК",
"id": 8
}
},
{
"id": 3,
"code": "ro",
"name": "Romana",
"pivot": {
"category_id": 3,
"language_id": 3,
"value": "aksessuari-dlya-noutbukov-i-pk-ro",
"id": 9
}
}
]
}
],
"translations": [
{
"id": 1,
"code": "en",
"name": "English",
"pivot": {
"category_id": 1,
"language_id": 1,
"value": "PC",
"id": 1
}
}
]
}
Controller:
return Category::with('children')
->with(array('translations'=>function($query) use ($lang_id){
$query->where('language_id',$lang_id);
}))
->where('parent_id',0)->first();
Model
class Category extends Model
{ ..
public function translations()
{
return $this->belongsToMany('App\Models\Translation','category_language', 'category_id' ,'language_id' )->withPivot('value','id');
}
public function children()
{
return $this->hasMany( 'App\Models\Category' , 'parent_id' , 'id' )->with('translations');
}
}
you can add condition in children method
public function children()
{
return $this->hasMany( 'App\Models\Category' , 'parent_id' , 'id' )->with('translations')->where('language_id', 1);
}
Dry7 answer was close to the one I've implemented later, so I upvoted him.
Finally in model I've added: ...->where('language_id',helper_SetCorrectLangIdForQuery());
and function helper_SetCorrectLangIdForQuery is using global helper of Laravel request()->lang . If lang=enz, than it takes default language from another helper.
I am working with laravel and I have basically these 3 related models in the following way: person model (Person.php), task model (Task.php) and post model (Post.php).
Person.php
public function tasks()
{
return $this->hasMany(Task::class);
}
public function posts()
{
return $this->hasMany(Post::class);
}
Task.php
public function person()
{
return $this->belongsTo(Person::class);
}
Post.php
public function person()
{
return $this->belongsTo(Person::class);
}
this is the way in which the models are related, now I have a method to recover a person and their tasks and posts that looks like this:
Person::with(['tasks','posts'])->findOrFail($id);
this returns the formatted data similar to these (it's an example):
{
"id": 1,
"name": "jhon",
"email": "jhon#gmail.com",
"created_at": "2018-09-14 12:07:35",
"updated_at": "2018-09-14 12:07:38",
"tasks": [
{
"id": 1,
"description": "task description",
"person_id": 1,
"created_at": "2018-09-18 21:07:48",
"updated_at": "2018-09-19 20:47:37",
},
{
"id": 2,
"description": "task description",
"person_id": 1,
"created_at": "2018-09-19 00:15:45",
"updated_at": "2018-09-20 15:28:58",
}
],
"posts": [
{
"id": 1,
"title": "post title",
"person_id": 1,
"created_at": "2018-09-14 12:08:52",
"updated_at": "2018-09-14 16:21:03"
},
{
"id": 3,
"title": "post title",
"person_id": 1,
"created_at": "2018-09-17 18:33:51",
"updated_at": "2018-09-17 18:33:51"
}
]
}
my question is this: is it possible to separate the result of the tasks and posts models in a different array, if this is possible as I should do ?, I want to have a result like this:
[
{
"id": 1,
"description": "task description",
"person_id": 1,
"created_at": "2018-09-18 21:07:48",
"updated_at": "2018-09-19 20:47:37",
},
{
"id": 2,
"description": "task description",
"person_id": 1,
"created_at": "2018-09-19 00:15:45",
"updated_at": "2018-09-20 15:28:58",
},
{
"id": 1,
"title": "post title",
"person_id": 1,
"created_at": "2018-09-14 12:08:52",
"updated_at": "2018-09-14 16:21:03"
},
{
"id": 3,
"title": "post title",
"person_id": 1,
"created_at": "2018-09-17 18:33:51",
"updated_at": "2018-09-17 18:33:51"
}
]
$a = DB:table('posts')->get();
$b = DB:table('tasks')->get();
$c = array_merge($a,$b);
see doc:
https://laravel.com/docs/5.7/queries
I've been struggling with a issue the last couple of days. I've just started using Laravel and are getting real fond of the Eloquent-syntax!
But there's a issue when I'm trying to get the correct relation between three models.
I've got this setup:
programs table contains
event_id
user_id
role_id
In my Event-model I've got
public function programs(){
return $this->hasMany(Program::class);
}
In my User-model I've got
public function programs(){
return $this->hasMany(Program::class);
}
In my Role-model I've got
public function programs(){
return $this->hasMany(Program::class);
}
And my Program-model contains
public function event(){
return $this->belongsTo(Event::class);
}
public function user(){
return $this->belongsTo(User::class);
}
public function role(){
return $this->belongsTo(Role::class);
}
And I need to get the following result
Events -> Users -> Role
In my controller I've got
$events = Event::with('programs.role.programs.user')->get();
Which is producing this:
{
"id": 2,
"name": "Concert: Freddy Kalas",
"description": "Freddy Kalas konsert",
"user_id": 2,
"time_from": "12.04.2017 22:00:00",
"time_to": "12.04.2017 23:00:00",
"created_at": "2017-03-20 18:28:44",
"updated_at": "2017-03-20 18:28:44",
"programs": [
{
"id": 2,
"event_id": 2,
"user_id": 2,
"role_id": 1,
"created_at": null,
"updated_at": null,
"role": {
"id": 1,
"name": "Camera operator",
"description": "Operates ordinary cameras or PTZ cameras",
"created_at": "2017-03-20 20:11:06",
"updated_at": "2017-03-20 20:11:06",
"programs": [
{
"id": 1,
"event_id": 3,
"user_id": 2,
"role_id": 1,
"created_at": null,
"updated_at": null,
"user": {
"id": 2,
"name": "Dummy Dum",
"email": "dummy#example.com",
"created_at": "2017-03-20 16:45:09",
"updated_at": "2017-03-20 16:45:09"
}
},
{
"id": 2,
"event_id": 2,
"user_id": 2,
"role_id": 1,
"created_at": null,
"updated_at": null,
"user": {
"id": 2,
"name": "Dummy Dum",
"email": "dummy#example.com",
"created_at": "2017-03-20 16:45:09",
"updated_at": "2017-03-20 16:45:09"
}
}
]
}
}
]
},
{
"id": 3,
"name": "Prøveproduksjon",
"description": "Prøveproduksjon med video og lyd",
"user_id": 1,
"time_from": "11.04.2017 13:00:00",
"time_to": "11.04.2017 17:00:00",
"created_at": "2017-04-03 17:12:37",
"updated_at": "2017-04-03 17:12:37",
"programs": [
{
"id": 1,
"event_id": 3,
"user_id": 2,
"role_id": 1,
"created_at": null,
"updated_at": null,
"role": {
"id": 1,
"name": "Camera operator",
"description": "Operates ordinary cameras or PTZ cameras",
"created_at": "2017-03-20 20:11:06",
"updated_at": "2017-03-20 20:11:06",
"programs": [
{
"id": 1,
"event_id": 3,
"user_id": 2,
"role_id": 1,
"created_at": null,
"updated_at": null,
"user": {
"id": 2,
"name": "Dummy Dum",
"email": "dummy#example.com",
"created_at": "2017-03-20 16:45:09",
"updated_at": "2017-03-20 16:45:09"
}
},
{
"id": 2,
"event_id": 2,
"user_id": 2,
"role_id": 1,
"created_at": null,
"updated_at": null,
"user": {
"id": 2,
"name": "Dummy Dum",
"email": "dummy#example.com",
"created_at": "2017-03-20 16:45:09",
"updated_at": "2017-03-20 16:45:09"
}
}
]
}
}
]
}
I can't get the models to relate to eachother - it seems. The preferred result that I want is that all the Events is tied with many users - and all the users for that event to be tied to one role. How can i accomplish this with Laravel and Eloquent?
Thanks for any responses!
EDIT:
To fetch the data i use the following code to generate the results above
$events = Event::with('programs.role.programs.user')->get();
Content of the programs table
# id, event_id, user_id, role_id, created_at, updated_at
'1', '3', '2', '1', NULL, NULL
'2', '2', '2', '1', NULL, NULL
This would mean that the user with an ID of 2 is only associated with event 3 with an role of 1 and event 2 with a role of 1. As you can see from the results both events has both role 1 and 2. Sorry for bad explanation..
Probably just try to make it one at a time and figure out what is returned.
#Fredrik Angell Moe said:
Got it working now by using:
$events = Event::with('programs.role')->with('programs.user')->get();
user with an ID of 2 is only associated with event 3 with an role of 1
and event 2 with a role of 1. As you can see from the results both
events has both role 1 and 2.
You are using two values. One is id of user and second is id of event.
Laravel can define realtion between only two models. That means in you query you are using the programe_id and event_id.
But user_id is getting neglected. So it will just add the user related to the model instead of filtering with the user_id.
The best way to solve this problem is instead of using the relation go for the raw query where you need to get relation between more than two models.