I'm having trouble getting a chained query to work for deleting a single record in 2 different columns in the user model. On submit, I want to delete the user's record in column A and column B only, nothing else.
DB::table('users')
->where('id', Auth::user()->id)
->select('column_A')->delete()
->select('column_B')->delete()
->update([
'column_A' => 'value',
]);
This actually deletes that user's entire record. I have also tried substituting select for value and then I'll get the error:
calling delete() on string
Thanks!
Try something like this:
DB::table('users')
->where('id', Auth::user()->id)
->update([
'column_A' => '',
'column_B' => ''
]);
I can use delete() only to delete whole rows, but not some information in that row.
Related
$collection = DB::table('collections')
->join('users','users.id','collections.user_id')
->get([value(md5(encrypt('collections.id'))), 'collections.name', 'collections.category_id', 'users.name as username', 'collections.price', 'collections.image'])->toArray();
return response()->json([
'collection' => $collection,
], 200);
I want to encrypt value of collections.id. It doesn't encrypt value(md5(encrypt('collections.id'))) says
Unknown column
'd0bfdf6d2c0d3a3bb3b9db20b5194e67' in 'field list'
You are currently using the md5 encrypt function on the string collections.id, so you are not encrypting the result of the query but the database column name, which is why you are getting that the column doesn't exist.
By the naming of the $collection variable, I would presume that you are only expecting one result, if so you can do as below otherwise you will have to loop through each row and encrypt the column value.
It's not the nicest way of doing it, it would be much nicer to use casting in a model class if you use models. You can read more about casting in the Laravel documentation https://laravel.com/docs/8.x/eloquent-mutators
Also, a note, if you are only expecting one row, use first() rather than get(), and if you are expecting several rows, use the variable name $collections as it makes the code easier to read as it tells readers that the query will return several collections rather than just one
$collection = DB::table('collections')
->select(['collections.id', 'collections.name', 'collections.category_id', 'users.name as username', 'collections.price', 'collections.image'])
->join('users','users.id','collections.user_id')
->first()
->toArray();
if ($collection) {
$collection['collections.id'] = md5(encrypt('collections.id'));
}
return response()->json([
'collection' => $collection,
], 200);
Hi I am working on a project Laravel where I need to update record in database by fetching last(latest) record against foreign key, The scenario is fetch latest record(row) and if its specific column (amendments_to) has NULL value update it with some string else insert a new record. Below is my code what it does is always updates last row only no matter what the value in amendments_to column is.
OrderResponse::where('send_id', $id)
->orderBy('id', 'desc')
->take(1)
->update(['amendments_to' => $request->comment]);
If you only are doing it with a single row at a time, i would simply do a more Eloquent approach. Laravel has a helper for latest() query.
$orderResponse = OrderResponse::where('send_id', $id)
->latest()
->first();
if (!$orderResponse->amendments_to) {
$orderResponse->amendments_to = $request->comment;
$orderResponse->save();
} else {
$newOrderResponse = new OrderResponse([
'amendments_to' => $request->comment,
'send_id' => $id,
// other fields
]);
$newOrderResponse->save();
}
I have a expiry_date (type=date) column in my table
$currentDate = date('Y-m-d');
$Data = Post::whereDate('expiry_date','<=',$currentDate)->where(['status' => 'active'])->orWhere(['p_id' => 3])->select('id','title','status','p_id','expiry_date')->orderBy('id', 'DESC')->get();
i want to filter data if current date is greater than expiry date then those record should not be shown but in my scenario i'm still getting record.
Any solution Thanks.
You must group orWhere clause in closure. Grouping in closure is like () in real query.
$Data = Post::whereDate('expiry_date','<=',$currentDate)
->where(function($query){
return $query
->where(['status' => 'active'])
->orWhere(['p_id' => 3]);
})
->select('id','title','status','p_id','expiry_date')
->orderBy('id', 'DESC')
->get();
But, because I don't know your project - i may wrong with grouping.
So I have question with eloquent. I fetch data like this:
$model::query()
->with([
'codes',
'codes.status',
'codes.company',
'codes.type',
'codes.item.serials',
])->get();
This returns all columns, but as soon as I provide select method to select certain columns my $model returns empty array
$model::query()
->with([
'codes' => function ($query) {
$query->select('code');
},
'codes.status',
'codes.company',
'codes.type',
'codes.item.serials',
])->get();
Why is this happening and how to fix this?
I have posts table (id, user_id, title) and Post model with this content
class Post extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
I want to get some post by id and also the user's information, so I use this query
$post = new Post();
$res = $post->where('id', 1)->select('id', 'title', 'user_id')->with([
'user' => function ($query) {
$query->select('id', 'name', 'email');
}
])->first();
It returns the data as expected, and i can access the post's info like $res->title, or the user's info like $res->user->email, but the problem is it makes 2 queries to the database
I would expect to have one query only
SELECT
`posts`.`id`,
`posts`.`title`,
`posts`.`user_id`,
`users`.`id`,
`users`.`email`,
`users`.`name`
FROM
`posts`
LEFT JOIN `users`
ON `posts`.`user_id` = `users`.`id`
WHERE `posts`.`id` = '1'
LIMIT 1
Please note, this is not the same as N+1 problem
https://laravel.com/docs/5.3/eloquent-relationships#eager-loading
I know I can manually do left join,
$res = $post->where('posts.id', 1)
->select('posts.id', 'posts.title', 'posts.user_id', 'users.email', 'users.name')
->leftJoin('users', 'posts.user_id', '=', 'users.id')
->first();
and it will have the one query as I need, but the problem is in the result all data from related table is in the same array (and besides, what is the point of defining/using relationships if i have to manually make a left join every time)
So, my question is how to get the post data with related tables with one query and result organized according to relations: I am curious what is the best practice in laravel and how experienced Laravel developers are doing this ?
Thanks
Eloquent never uses JOINs to retrieve relationship data, but instead uses seperate queries and links the data together in PHP objects. Therefore, you will always have one extra query for each relationship. Also, Eloquent mostly loads all columns (using *).
To link them together, you have to stop using the query builder and instead use Eloquent directly:
$post = Post::find(1)->load('user');
If you insist on using JOINs, you will have to continue using the query builder.
That is eager loading.
You are using
->with([
'user' => function ($query) {
$query->select('id', 'name', 'email');
}
])
In eager loading, what happens is first run above query and get all the users matching the query.
Then the result is applied to the outer query which is
$post->where('id', 1)->select('id', 'title', 'user_id')->with([
'user' => function ($query) {
$query->select('id', 'name', 'email');
}
])->first();