create a json joining queries in laravel - php

I have two related tables, Areas and subareas. Each area has many subareas. I need to return a json where for each area all the subareas are shown in a json, in the way shown in the image.
I'm using laravel 5.4 and I do not know how to do it.
Area Model:
Subarea Model:
My Code:
sorry. I am a newbie in programming and new in laravel.

As you have relationship set between the models, you can just do :
$areas = Area::with('subareas')->get();
This will give you all areas and a collection inside each area with it's respective subarea.
You can go one step further and use API Resource setup to structure the json response as you would like.

Make a 2D array to convert it to JSON
Something like:
$areas = \Area::all();
$sub_areas = $areas->subAreas; // relationship
Iterate $areas using foreach loop and against each item, put it's subareas to some array
and finally json_encode that array

Related

Order three different and unrelated models in laravel

I have three different models and I want to filter them and return them in the same object by creation date. The problem is that the filter must be applied on all models at once and not on each model successively.here are my three models, I don't know how to continue, need help
$quick = Model::with('user')->orderByDesc('id')->get();
$simple = Models::with('user')->orderByDesc('id')->get();
$suivi = Modelss::with(['user', 'position'])->orderByDesc('id')->get();
If there is no link in between the models and you want to retrieve data by ordering them all together. You need to use Collections for this.
What you can do after your 3 line of code is:
$quickSimpleMerged = $quick->merge($simple);
$merged = $quickSimpleMerged->merge($suivi);
$result = $merged->all();
Now that you have 1 collection including all data from 3 models of yours, you can simply run:
$result->sortByDesc('created_at');

Laravel 8 - how to fetch data from the database using an object as a "where" condition?

im new in laravel programming and im trying to do something with laravel Eloquent.
So i have 3 tables, dev, dev_project(many to many) and project.
i need to see in which projects the dev is part of, using the dev_project table, and get the corresponding id from projects.
after that i need to go to the table project, and use the id that I got from the many-to-many table to get the corresponding name of the projects in which that same dev is part of.
First im fetching data from my DB into a variable
$devproject = DB::table('dev_project')->where('id_dev', '=', Auth::user()->id)->get();
And then Im trying to get the data from the project table where the id is the same from the one that i fetched before
return Project::where('id', $dev_project->id_project);
The problem here is that the variable dev_project is an object, and i cant use a foreach and store the data that i want to return inside an array.
So how can I get all the data that i want in the same object.
I appreciate any help, Thank you.
Here, $devproject is a Collection, not a single row. $dev_project->id_project is not a valid property.
If you want the first result's id_project, then the syntax is $devproject->first()->id_project.
If you want a Collection of each of $devproject 's id_project, then the syntax should be $devproject->pluck('id_project').
With that in mind, your query should either be
return Project::where('id', $dev_project->first()->id_project);
or
return Project::whereIn('id', $dev_project->pluck('id_project'));
As harish durga suggests, a relationship would save you the trouble of writin these queries.
# Dev Model
public function projects()
{
return $this->belongsToMany(Project::class, 'dev_project', 'id_project', 'id_dev');
}
# Project Model
public function devs()
{
return $this->belongsToMany(Dev::class, 'dev_project', 'id_dev', 'id_project');
}
# Get all devs with associated projects:
$devs = Dev::with('projects')->get();
foreach ($devs as $dev) {
echo $dev->...
foreach ($dev->projects as $project) {
echo $project->...
}
}

Get objects in the other part of a N-N relationship that are not related to the actual object

I have a N-N relationship between Films and Genres, and I am trying to get from a $film the objects in the table Genres that are NOT in $film->genres().
I have looked for trying to do something like Genres:all() - $film->genres() or to do a loop in order to erase everyone but there is no Collection method that allows me to do that.
How can I do that?
Thanks.
I finally found the solution:
$film = Film::findOrFail(1);
$hasGenres = $film->genres()->pluck('id');
$doesntHaveGenres = Genres::whereNotIn('id',$hasGenres)->get();

Replicating multiple models at once

I am using Laravel 4.2.
If I want to duplicate a model I can use the following:
$newModel = $currentModel->replicate();
$newModel->save();
However I have this inside a loop, like so:
foreach ($this->models as $currentModel) {
$newModel = $currentModel->replicate();
$newModel->save();
}
Which obviously causes a several DB calls. I want something more efficient, so I can loop through my models and then outside of the loop use one DB call to write them all in one go.
In Laravel is there a way to replicate multiple models in one go?
You can use the insert statment of DB query builder like this :
foreach ($this->models as $currentModel) {
$newModel = $currentModel->replicate()
$newModels[] = $newModel->toArray();
}
DB::table('table_name')->insert($newModels);
No it not possible duplicate more than one model, you can see in the api documentation:
https://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_replicate
So if you would duplicate X models you need loop them and you can speific (with array parameter) wich columns you would like to not copy

How can you update and create a new row in Laravel from a JSON object with relationships?

I started using Laravel yesterday, the ORM seems powerful. Does it have any way of updating rows in related models? This is what I tried:
Step 1: Generate a JSON object with the exact structure the database has. The JSON object has certain fields that are subarrays which represent relationships in the database.
Step 2: Send the JSON object via POST to Laravel for processing, here it gets tricky:
I can change the JSON object into an array first
$array = (array) $JSONobject;
Now I need to update, I would expect this to work:
Product::update($JSONobject->id,$array);
But because the array has subarrays, the update SQL that is executed cannot find the sub-array column in the table, it should instead look for the associated table. Can this be done? Or do I have to call the other models as well?
Thanks in advance!
This is something that Eloquent does not handle for you. The array that you supply to the update() method should contain columns only for, in your case, the Product model. You might try something like this to update relations. This is all off the top of my head and is by no means tested. Take it with a grain of salt.
$update = (array) $JSONobject;
$relations = [];
foreach ($update as $column => $value)
{
// If the value is an array then this is actually a relation. Add it to the
// relations array and remove it from the update array.
if (is_array($value))
{
$relations[$column] = $value;
unset($update[$column]);
}
}
// Get the product from the database so we can then update it and update any of the
// the products relations.
$product = Product::find($update['id']);
$product->update($update);
foreach ($relations as $relation => $update)
{
$product->{$relation}()->update($update);
}
The above code assumes that the key for your nested relation arrays is the name of the relation (method name used in your model). You could probably wrap this up in a method on your Product model. Then just call something like Product::updateRecursively($JSONobject); I'm terrible with names but you get the idea.
This probably won't work with more complex relations either. You'd have to take it a few steps further for things like many to many (or probably even one to many).

Categories