how to get all related model IDs in Yii? - php

Suppose $model hase some items (one to many relationship), So in Yii $model->items returns an array of item models. How can I get an array of IDs of related items. This means each element of returned array is an integer.

You should simply write your own function for this, e.g.
public function getItemsIDs()
{
$ids = array();
foreach($this->items as $item)
$ids[] = $item->id;
return $ids;
}
After you just have to call $model->itemsIDs.
EDIT : as darkheir said in its comment, you should consider using DAO.

Here is an example of direct query, run from Model:
$this->getDbConnection()->createCommand("SELECT id FROM items WHERE model_id = :modelId")->bindParam(":modelId", $model->id, PDO::PARAM_STR)->queryColumn();
In result you will get numeric Array() with IDs from the table as values.

Another variant.
Yii::app()->db->createCommand("SELECT id FROM items WHERE model_id=".$model->id)->queryColumn()
This will get all IDs from table as array

Related

Dynamic accessing of the php list

I have 2 tables in the database employee(Ename,id,manager_id) and manager(name,id).1 manager has multiple employees under him.
The first line extracts all the employees under 1 manager and creates a list of it. Now, I wish to extract the name of each employee name from the retrieved employee id. How do i access each element of the list? This is what i have tried and it throws errors
$emplyeeId=DB::table('employee')->where('manager_id', $givenManagerId)->lists('id');
for ($i=0;$i<listCount;$i++)
{
$Ename = DB::table('employee')->where('id', $emplyeeId($i))-> value('Ename');
}
By looking at the docs (and scroll down a little bit, you find a method named pluck. This will return an array with all the values of the given column.
In your case this would be:
$names = DB::table('employee')->where('manager_id', $givenManagerId)->pluck('Ename');
// This will return the following array:
['Kevin', 'Tom', 'Tina', ...]
Laravel pluck method ,for example get just name from data
$names = DB::table('employee')->where('manager_id', $givenManagerId)->pluck('Ename');
Second method with array_filter
$names = DB::table('employee')->where('manager_id', $givenManagerId)->get()->toArray();
$justNames=array_filter($names, function ($ar) { return $ar['Ename']; });

Updating multiple id from array list with eloquent

I've passed to the controller an array of id and it is collected inside the student variable. I want to update the database column "lecture_id_FK" for each id in the array. I'm not sure as to how to use the array id to find the students. New in laravel.
Controller
public function setLecture($lecture,$student)
{
$students = student::whereIn('student_id', $student)->get();
$students->lecture_id_FK = $lecture;
$students->save();
//if i type "return $student" will produce -> ai160064,ai160065
}
The whereIn method takes an array as the second argument. You can get all students by using the explode function. Following getting all the records you want to update, you can do an update on all of them with the update method in laravel. With that you might be left with some code like the following:
public function setLecture($lecture,$student)
{
$studentIds = explode(',', $student);
return student::whereIn('student_id', $studentIds)
->update(['lecture_id_FK' => $lecture]);
}

why foreach print just one value in laravel?

I have a method:
public function winnerDetails()
{
$winners = DB::table('winners')->get();
//dd($winners);
foreach ($winners as $winner) {
$qrMainId = $winner->qrdetails_id;
}
dd($qrMainId);
}
dd($winners); returns to value of array but when i use foreach its returns one value. How can i get who value returns with foreach loop?
dd($winners) output:
and dd($qrMainId); return one value 44. But it should return another value of array 35; Thanks in advance.
To get array of ID's use
foreach ($winners as $winner) {
$qrMainId[]= $winner->qrdetails_id;
For just value use
$qrMainId='';
foreach ($winners as $winner) {
$qrMainId.= $winner->qrdetails_id;
If you want to accomplish this task in a Laravel way use the pluck method to map the array for the key that you want
<?php
public function winnerDetails()
{
$winnersId = DB::table('winners')->get()->pluck('qrdetails_id');
dd($winnersId);
}
I think you are not leveraging the power of Laravel here. Obviously, I don't know what you are trying to do but here are some pointers.
You should probably be making a model for the winners table now models in Laravel return Collections as does the DB facade you are using now. Now the Collection class contains alot of usefull helpers like pluck
At this point it becomes as easy as Winner::all()->pluck('id') and you got yourself an array of id's.
And if you would like to get them comma seperated or anything like that you can use the implode
And you would get Winner::all()->implode('id',',');
$qrMainId is a variable not an array.
It is modified in the foreach during every loop.
So your code has always the last element of the array.
Use an array to collect values like
$qrMainId[] = $winner->qrdetails_id;
or sql select directly the field you want.

Laravel getting collection ordered by relationship table

I have 2 tables, one is magazine and the other is issues. I have set up their relationship like this:
Magazine model:
public function issues()
{
return $this->hasMany('App\Issue')->orderBy('date', 'desc');
}
Issue model:
public function magazine()
{
return $this->belongsTo('App\Magazine');
}
I have a query where I get magazines ordered by a column and then in foreach loop I am getting the first issue of each magazine and storing it in array:
$magazines = Magazine::with('issues')->orderBy('order')->get();
foreach ($magazines as $magazine)
{
$issues[] = $magazine->issues()->first();
$images[] = $magazine->issues()->first()->image;
}
But, I would like to make a collection instead of an array. I am not sure how can I do that kind of query or is there a way to somehow store values to a collection in a foreach loop?
There are several ways of doing this.
You can turn an array into a collection by doing the following.
$issuesCollection = collect($issues);
$imagesCollection = collect($images);
You could also initialize an empty collection and then use the push() method to append items to it. Check the documentation
Just use the map function:
$magazines = Magazine::with('issues')->orderBy('order')->get();
$firstIssues = $magazines->map(function($magazine) {
return $magazine->issues->first();
});
$images = $firstIssues->map(function($issue) {
return $issue->image;
});
The map method iterates through the collection and passes each value
to the given callback. The callback is free to modify the item and
return it, thus forming a new collection of modified items

Laravel model data foreach

I have the following line $totalRequests = \App\LoanRequest::all(); which returns all records, Along a model Applicant which have One to Many relation with LoanRequest.
So i can access applicants data with $totalRequests[0]->applicant->region for with foreach().
Question :
Now i want all the distinct regions in the Applicant or table applicants from the LoanRequest::all() model and want to push those regions to an array which then i can pass to a view.
What i am trying :
$totalRequests = \App\LoanRequest::all();
foreach($totalRequests as $applicant){
$filterMeta = [];
array_push($applicant->aplicant->region, $filterMeta);
}
It throws:
Indirect modification of overloaded property App\Applicant::$region has no effect
If you want to push the region to the array, you're using the wrong argument order. Also, shouldn't you be initalising the filter meta array outside of the loop?
$totalRequests = \App\LoanRequest::all();
$filterMeta = [];
foreach($totalRequests as $applicant){
array_push($filterMeta, $applicant->aplicant->region);
}

Categories