Order three different and unrelated models in laravel - php

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');

Related

create a json joining queries in laravel

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

How to compare Models by ID and not content

I am using Laravel 5.1.
I have two collections, $collectionA and $collectionB. Each collection contains Flashcards which extends Model. I am trying to do something like this, but it isn't working:
$collectionA->intersect($collectionB)
The reason is that while each Flashcard has the same id, their pivot tables are different. Ideally, I would like to ignore the pivot table and compare by ids only. Is there a way to do this?
Perhaps there's a more efficient way to do this, but you could reduce $collectionB to an array of its ids, then filter $collectionA to only those elements:
$bIds = $collectionB->lists('id')->toArray();
$intersected = $collectionA->filter(function($item) use ($bIds) {
return in_array($item->id, $bIds);
}

How Do I Append Additional Yii 1.16 ActiveRecord Models?

I am familiar with using Yii to call records, but how would I go about taking an existing active record model and appending more information to it using a different query?
For example:
$user = User::model()->findByPk(1);
$user[] = User::model()->findByPk(2);
Basically, I am trying to add model $user1 + $user2. In this type of example, I want to have both users 1 and 2 in the same $user model. (I have not actually tried the code above, but I do not think it would work like that.) The information obtain from both requests would be exactly the same format.
Be aware that that I am not trying to get both users. I know how to do that. In this question, I am attempting to take an existing model and add more data to it to form one model by merging the two models together.
There is no built in Yii way to do what you are trying to accomplish. Instead, you can your model with some custom enhancements.
private $additionalUsers = array();
public function addAdditionalUser($user)
{
$this->additionalUsers[] = $user;
}
public function getAdditionalUsers()
{
return $this->additionalUsers;
}
Then you use this as follows:
$user = User::model()->findByPk(1);
$user->addAdditionalUser(User::model()->findByPk(2));
However, without knowing more of what you mean by "merge" the models, this may or may not be what you are looking for. An example of how you expect to use the merged model would be useful if this answer doesn't suit your needs.
You can do this:
$users = array();
$user1 = User::model()->findByPk(1);
$user2 = User::model()->findByPk(2);
array_push($users, $user1);
array_push($users, $user2);
Now $users is an array that contains two objects.
You can use
$users = User::model()->findAllByPk(array(1,2));
which will return and array of usermodels

Retrieving computed subset of columns in doctrine

I want to develop a RESTful API based on Slim Framework and Doctrine 2. I have a detailed permission management. So I have permissions defined as:
role:admin|entity:person|column:name|write:1
Im considering the most effective way to implement the right management into the web service.
Therefore I need to filter a computed subset of columns when building my query. What is the best place to do that, still enabling me to use all the default methods like findAll() etc. I could of course filter my fields like below:
$all = Article::createQuery('a')->getArrayResult();
/*this is getting ALL the fields -it would be better to filter before
retrieving from the db
*/
$allFiltered = array();
foreach($all as $index=>$article){
$filteredArticle = new Article();
foreach($user->getPermission('Article','r') as $permission){
$column = $permission->column;
$filteredArticle->$column = $article->$column;
}
$allFiltered[$index]=$filteredArticle
)
$app->response->setBody(json_encode($all));
Is there a way to do this at one place for all retrieving methods ?
Doctrrine2 can select partial object doc
You can fetch all permitted columns and just concatenate with a query ...

Yii fetching records by type

I'm wondering if Yii has an efficient method for grouping items by type.
Let's say I have the following model:
Tag
------
id
name
type_id
And let's say there are 5 different types of Tags. I want to be able to display in my index all tags in sections by type_id. Is there a Yii-way of accomplishing this?
Outside a framework I would write a function such that results fetched from the DB were stored like this:
$tags[$typeID][] = $tag;
Then in each section I could do something like:
foreach( $tags[$typeID] as $tag )
{
// Here are all tags for one $typeID
}
But I'm having difficulty figuring out how to do this in Yii without:
A) looping through the entire result set first and rewriting it or,
B) running 5 different queries.
When using ActiveRecord simply specify the "index" in the DBCriteria. So in a query do:
ActiveRecordClass::model()->findAll(array('index'=>'type_id'));
That will return an assoc array that your after. TBF it probably executes exactly the same code, but this is obviously easier to use that performing it everywhere.
Assuming that your active record class is called MyActiveRecordClass, the simplest approach should be sufficient:
$models = MyActiveRecordClass::model()->findAll();
$groupedModels = array();
foreach ($models as $model) {
$groupedModels[$model->typeID][] = $model;
}
If you give more specific information about how you intend to display the grouped results it might be that a better approach can be worked out.

Categories