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']; });
Related
So I am quite new to Laravel, and I have a situation, where I am trying to gather data from a pivot table (contains 2 foreign keys only) in order to retrieve data from other tables.
Before everything, I'd like to note, that word "campaign" is the same as "box". Simply it differs in database and front.
I have multiple boxes, that contains specific gifts.
I have set the URL of the box to be something as such: http://127.0.0.1:8000/box/1
http://127.0.0.1:8000/box/2
etc..
I have done so, by simply using a button with the {id}:
View the box
My plan is, to print out only that specific boxes gifts (right now, all boxes print out all gifts).
I have tried to use the ->where option within my function, although, it seems that I can't try equaling to the campaigns ID.
Incorrect code:
function box(){
$data = array(
'list'=>DB::table('campaigns_gifts')
->join('gift_items', 'gift_items.id', '=', 'campaigns_gifts.gift_foreignK')
->select('gift_items.*')
->where($campaign_foreignK = '{id}')
->get()
);
return view('DBqueries.boxView', $data);
}
My question is, how can I specifically return data, that only belongs to that specific box, since I am not able to use mysql where option.
For reference, these are the database tables:
Basically, I would need to match my URL's id with campaign_foreignK
Thank you in advance.
First of all, yout need to start to use Laravel Eloquent Models.
But doing by your way (the hardest):
You need to create a route in web or api, something like that:
Route::get('/box/{id}', [BoxController::class, 'view']);
Then you need to put this function on your controller:
function view($id){
/**
* You can do it by 2 ways:
* 1 - Do a where in the result of DB query (the bad way)
*/
$list = DB::table('campaigns_gifts')
->join('gift_items', 'gift_items.id', '=', 'campaigns_gifts.gift_foreignK')
->select('gift_items.*')
->where($campaign_foreignK = '{id}')
->get();
$list = (array)collect($list)->where('abc', 123);
/**
* Or the second way (the best is to use the Eloquent, but using DB the following is the best)
* 1 - Get the relations:
* Is git_items id the key for gift_foreignK ? i'm supposing that is it! so....
*/
$giftsIds = array_values((array)DB::select("select * from campaigns_gifts where campaign_foreignK = $id"));
$giftsIdsString = implode($giftsIds, ',');
$list = (array)DB::select("select * from gift_items where id in ($giftsIdsString)");
return view('DBqueries.boxView', ['list' => $list]);
}
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]);
}
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);
}
I have a field in my model Person called jobs that I'm casting as an array. jobs is an array of ids related to a Jobs table. I want to be able to query Person and return all that have a certain id in their jobs array. I see that Laravel has a whereIn clause which checks if a database value is in an array but I need the opposite - to check whether a database array contains a value.
Am I stuck having to use where('jobs', 'like', '%"' . $job_id . '"%')?
I'm not sure there's an opposite however if you're simply looking to make the query a bit more reusable, you could make it a local scope by adding this to your Person model:
/**
* Scope a query to only include persons with given job id.
*
* #return \Illuminate\Database\Eloquent\Builder
*/
public function scopeHasJob($query, $jobId)
{
return $query->where('jobs', 'like', "%\"{$jobId}\"%");
}
The name of the scope hasJob may interfere with the parent QueryBuilder method has so you might have to come up with a different name for it.
Now you can use Person::hasJob($job->id). However rather than storing the job ids in a column as an array, you should consider creating a pivot table to map the relationships between a person and job. You can do this using php artisan:
php artisan generate:pivot persons jobs
php artisan migrate
Then you need to add the relationship into your Person model:
/**
* The person's jobs
*/
public function jobs()
{
return $this->belongsToMany('App\Job');
}
So you can query your Person model by Job like this:
Person::whereHas('jobs', function ($query) {
return $query->whereId($job->id);
});
Laravel includes whereJsonContains(): So your field jobs that you
are casting as an array, that can query as :
->whereJsonContains('jobs', 3)
That way worked for me ...
I am adding a little more info to Zubayer Hossain's answer
The data types have to match:
// [1, 2]
->whereJsonContains('players', 1) // Works.
->whereJsonContains('players', '1') // Doesn't work.
// ["1", "2"]
->whereJsonContains('players', '1') // Works.
->whereJsonContains('players', 1) // Doesn't work.
whereJsonContains can be used in cases where we need to check if a value matches a json encoded field in our table.
Courtesy : https://newbedev.com/php-wherejsoncontains-and-with-laravel-example
You could use something like this query.
$k = ["359045532","359079612","359079372","359081292","359081052","359086332","359086092","359111892","359111652"];
Modal::whereIn('myitems', $k)->get();
<!-- If you have a collection of value like this: -->
$category_id = 1,2,3,...;
$category_id = $_POST['category_id'];
$myArray = explode(',', $category_id);
<!-- If you already have array data you can pass this to the following query -->
$data = DB::table('tablename')->select('*') ->whereIn('catcode', $myArray)->get();
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