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]);
}
Related
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']; });
I have found this:
Move data from one MySQL table to another
But in Laravel it's a bit different. Like him I want a button which deletes a row in a table like this one:
(Updated picture)
Just to have an example. After he hit the button it should move the shown row into the database just like it is shown here and delete it afterwards. I really don't know how to start something like this in Laravel and I really can't find something related.
Maybe this will make it more clear:
$user_input = $request->userInput
$scores = DB::table('cd')
->join('customers', 'cd.fk_lend_id', '=', 'customer .lend_id')
->select('cd.fk_lend_id','cd.serialnumber','users.name', 'cd.created_at as lend on')
->where('cd.fk_lend_id',$request->$user_input)
->get();
Suppose you have two tables: firsts and seconds
For Laravel you must have two Models for these two tables: First and Second respectively.
Now, in your controller,
//import your models
use App\First;
use App\Second;
//create a function which takes the id of the first table as a parameter
public function test($id)
{
$first = First::where('id', $id)->first(); //this will select the row with the given id
//now save the data in the variables;
$sn = $first->serialnumber;
$cust = $first->customer;
$lendon = $first->lend_on;
$first->delete();
$second = new Second();
$second->serialnumber = $sn;
$second->customer = $cust;
$second->lend_on = $lendon;
$second->save();
//then return to your view or whatever you want to do
return view('someview);
}
Remember the above controller function is called on button clicked and an id must be passed.
The route will be something like this:
Route::get('/{id}', [
'as' => 'test',
'uses' => 'YourController#test',
]);
And, your button link like:
Button
This might be a simpler way to do the Laravel "move record" part of this.
use App\Http\Controllers\Controller;
use App\Models\TableOne;
use App\Models\TableTwo;
use Illuminate\Http\Request;
class MoveOneRecord extends Controller
{
public static function move_one_record(Request $request)
{
// before code
// get id
$id = intval( $request->input('id', 0) );
// grab the first row of data
$row_object = TableOne::where('id', $id))->first();
// check if we have data
if (empty($row_object)) { throw new Exception("No valid row data."); }
// convert to array
$row_array = $row_object->toArray();
// unset the row id (assuming id autoincrements)
unset($row_array['id']);
// insert the row data into the new table (assuming all fields are the same)
TableTwo::insert($row_array);
// after code
}
}
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
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