I want to update data only in pivot table in Laravel 8. All columns are foreign keys. While run the following query, the data in pivot table has been updated but Laravel form give the following error.
Error:
Call to a member function where() on int
Controller:
DB::table("student_topic_examiner")->update([
"internal_id" => $internal->id,
"external_id" => $external->id])
->where("roll_number", "=", $request->input('roll_number'));
Database pivot table is as pivot table.
Please guide.
The problem is that you are calling where() after update().
update() returns a integer (1 if something was updated, 0 otherwise).
It means that you code translates to (1)->where("roll_number", "=", $request->input('roll_number')).
If you only want to update the rows where this condition is true:
->where("roll_number", "=", $request->input('roll_number'))
Then, call it before update():
DB::table("student_topic_examiner")
->where("roll_number", "=", $request->input('roll_number'))
->update([
"internal_id" => $internal->id,
"external_id" => $external->id]
);
Related
I try to check if a column from a relationship table is null, . But with my current code I get an error.
The column is "best_match" in the second whereNotNull.
SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry
for table "questions"↵LINE 1:
$questions = Model::whereNotNull('question_id');
if($excepted_questions){
$questions->whereNotIn('id', $excepted_questions);
}
$questions->where('votes', '!=' , $confidence_specs->votes)
->orWhere('weight', '!=' , $confidence_specs->weight)
->with('questions')
->inRandomOrder();
//HERE I try to check if that column is null or not
if($confidence_specs->best_match){ // this can be true / false ,if is true I check if that column is null
$questions->whereNotNull('questions.best_match');
}
$questions->limit($nr_of_questions)
->get();
You will have to use whereHas to use where statement with the relationship model or you must have joined the table.
Otherwise just using where statement won't work on multiple tables.
For more information check the docs Querying Relationship Existence
So your query should have been
if($confidence_specs->best_match) {
$questions->whereHas('questions', function($query) {
$query->whereNotNull('best_match');
});
}
with will just eager loads the model it doesn't let you perform MySQL query on it.
How can I add in conditional the value of the query i'm using on when function of eloquent laravel?
Here's what I want to happen
$user = User::when('logged' == '3', function ($q){
$q->where('role', 'admin');
)}->get();
As you can see I want to get the role admin only when the column logged is equal to 3 how can I do this one ? thank you.
P.S.
just an example query. thank you.
This is not how when works,
the first condition 'logged' == '3' will always return false;
So it will not use the closure query, directly use get() method, and return all the User's records;
You need to do it like this:
$user = User::where(function($q) {
$q->where(['logged' => 3, 'role' => 'admin'])
})->orWhere('logged', '!=', 3)->get();
You may only want to apply a where statement if a given input value is present on the incoming request. In short you first condition is not base on your table field but base on the request you have. So #TsaiKoga answer's is correct.
The when method only executes the given Closure when the first parameter is true. If the first parameter is false, the Closure will not be executed.
Please read docs here when
I have two database tables items and measurement_units - item has measurement unit.
Now the problem is I want to select a particular column from items and some column from measurement_unit. I want to use Eager loading
e.g.
$items_with_mu = Item::with("measurement_unit")->select(["item_name", "item_stock"])->first();
When accessing measurement_unit. It returns null. Without the select function it returns data(measurement_unit).
$items_with_mu->measurement_unit;
can anyone help me and sorry for my English.
Try this
Item::with(['measurement_unit' => function($q) {
$q->select('id','unit_column'); //specified measurement_unit column
}])
->select('id','measurement_unit_id','item_name')
->get();
If your laravel version is >=5.5 then you can write in a single line
Item::with('measurement_unit:id,unit_column')
->select('id','measurement_unit_id','item_name')
->get()
You have to select the primary column of the main model like below.
items_with_mu = Item::with("measurement_unit")->select(["item_name", "item_stock", "primary_key"])->first();
I have a reference table with the following columns:
-user_id (foreign key)
-location_id (foreign key)
-skill_level
-court_id
I can update the skill_level pivot column value in the above table with:
$user = User::find($user_id)
$user->locations()->updateExistingPivot($location_id, array(
'skill_level' => $new_value
));
I would like to add something akin to a wherePivot() to the above so that only records that matches a certain court_id (in addition to user_id and location_id) are updated. Something similar to:
->wherePivot('court_id', '=', $court_id);
How would I do this with an updateExistingPivot() call?
I ended up using newPivotStatement() - which allows you to start a chain of statements off of the pivot table.
Instead of using updateExistingPivot(), the call would look like:
$user->locations()->newPivotStatement()->where('location_id', '=', $location_id)
->where('court_id', '=', $court_id)->update(array(
'skill_level' => $new_value
));
I am having 2 tables, users and profiledetails
I am able to run Join query and access the data and send to view.
But when I am manipulation the field 'dob' (date format) in profiledetails table. No Success, Please check the code below ,
webpagesConroller:
$users = DB::table('users')
->join('profiledetails', 'users.id', '=', 'profiledetails.user_id')
->select('users.*', 'profiledetails.dob')
->get();
$age = $users->dob->diffInYears(Carbon::now());
return view('webpages.index',compact('users'))->with($age);
View:
<li class="cate_head">Age : {{ $age}}</li>
Error:
Trying to get property of non-object
I have model Profiledetails added the mutators as below,
public function getAge(){
return $this->dob->diffInYears(Carbon::now());
}
public function getDOB(){
return $this->dob->format('d-m-Y');
}
Can I not use this method on another controller for Ex- webpagesController, If yes How.
Since you are using a raw query, the data returned is not an object but an array with the data.
Also you did not limit the query, meaning it could return multiple rows.
You'll probably need to get the data from the $users as:
//with the possibily of multiple rows. Index is the row which has to be used
$users[index]['dob']
//when you are sure it only returns one row
$users[0]['dob'] // or $users['dob'] not sure as of the moment
You want to check the differences with Carbon.
So you will probably need to make a Carbon object of the dob result and check it against the Carbon::now.
$age = Carbon::createFromFormat('Y-m-d', $users[0]['dob'])->diffForHumans();
// diffForHumans() uses the local time
Note that this only gets the age for one row (the index or the first because of [0]).
If you want to do it for every row use a for or foreach where you set the $users->age for every $user. But as these are not object/models but raw data, this will not work.
Hope this helps your question a bit