Eloquent model updating more rows that it should laravel php - php

I have a table without primary key that looks like this:
user_id
config_key
config_value
2296
config_key_1
config_value_1
2296
config_key_2
config_value_2
2296
config_key_3
config_value_3
2296
config_key_4
config_value_4
And every time I try to update one value from that table, for some reason the rest of the table is updated with the same values, like this:
user_id
config_key
config_value
2296
config_key_1
config_value_1
2296
config_key_2
config_value_1
2296
config_key_3
config_value_1
2296
config_key_4
config_value_1
My query looks like this:
$ConfigValue = AppUserConfig::where('user_id', 2296)
->where('config_key', 'config_key_1')
->first();
$ConfigValue->config_value = config_value_1;
$ConfigValue->save();
I just basically need to update one row of my table, from this:
user_id
config_key
config_value
2296
config_key_1
config_value_1
2296
config_key_2
config_value_2
2296
config_key_3
config_value_3
2296
config_key_4
config_value_4
To this:
user_id
config_key
config_value
2296
config_key_1
new_custom_value
2296
config_key_2
config_value_2
2296
config_key_3
config_value_3
2296
config_key_4
config_value_4
But not sure, what is happening :(
Both solutions pretty much solved it, thanks, everyone.

There's nothing weird going on, when you update a record using Eloquent, your update statement would use the primary key to identify that record, we can just assume that it tries to update all rows with id 2296. you can use debug tools like clockwork or telescope to verify the actual SQL statement queries when you run your code
You can also try using Query builder for update statement
e.i.
DB::table('app_user_config_whatever')
->where('user_id', 2296)
->where('config_key', 'config_key_1')
->update(['config_value' => 'config_value_1']);
but the best approach would be to create a proper relationship between user and config, like having the config belognsTo a user, then you can perform something like
$user->config()
->where('config_key', 'config_key_1')
->update(['config_value' => 'config_value_1']);
or
$user->config()
->updateOrCreate(
['config_key' => 'config_key_1' ],
['config_key' => 'config_key_1', 'config_value' => 'config_value_1']
);

you can update by using update query like this
$ConfigValue = AppUserConfig::where('user_id', 2296)
->where('config_key', 'config_key_1')
->update(['config_value'=>'config_value_1']);

Related

Problem with populating database column with seeding in Laravel

I need to populate my database column from seeding. I have 'interested_in' column in user_profiles table and I need to populate it with according id from 'value_id' column from user_interests table. Both user_profiles and user_interests table are connected to users table ('user_id' column is in both tables). So if the value of 'value_id' column is for example 1 it needs to be 1 in 'interested_in' column, I need help on how to populate that 'interested_in' column from seeders. 'value_id' column is already populated. Here are my tables and example data and my code so far but it doesn't work currently, it shows 'Array to string conversion' error.
user_interests table
user_id field_id value_id
1 1 1
user_profiles table
id user_id interested_in
1 1 and here needs to be 1, to associate value_id (1) from user_interests table
UserProfileTableSeeder.php
class UserProfileTableSeeder extends Seeder
{
use ChunkSeeder;
public function run()
{
$users = User::all()->pluck('id');
$user_interests = DB::table('user_interests')->select('value_id')->where('field_id', 1)->get();
$user_interests_values = $user_interests->pluck('value_id')->toArray();
$seed = [];
foreach ($users as $userId) {
$seed[] = factory(UserProfile::class)->make(
[
'user_id' => $userId,
'interested_in' => $user_interests_values, // Shows array to string error!!!
]
)->toArray();
}
$this->seedChunks($seed, [UserProfile::class, 'insert']);
}
}
That's why $user_interests_values is an array as you can see in this line (at the end):
$user_interests_values = $user_interests->pluck('value_id')->toArray();
Try in the factory to change $user_interests_values to current($user_interests_values) or probably $user_interests_values['id'] or whatever.
PS: I am not really sure what's inside $user_interests_values, you can see it with a dd() and running the migration then (don't worry, the migration won't be successful because of the dd() and you will be able to run it later again until it finishes properly.
By the way, I recommend you to do something more legible than you did in your rum() method. I mean, something like this:
$interest = factory(UserInterests::class)->create();
factory(UserProfiles::class, 20)->create([
'interest' => $interest->id,
]);

fetch and push the data in new table

I have the table 'project','user' and 'role_mapping'.I want to to fetch the project_owner_id from the project table and push the user_id which is fetched from user table and role_id=1 in role_mapping table.one project owner has multiple project.so I want to restrict duplicate entry. I want to do it in laravel controller controller.
project table
project_id project name project_owner_id
1 DEC01
2 DEC02
3 DEC01
user table
id user_string
1 DEC03
2 DEC01
3 DEC02
role_mapping table
user_id role_id
2 1
3 1
$heads = DB::table('project')
->join('users', 'project.project_owner_id', '=', 'users.user_string')
->select('project.project_owner_id','users.id as user_id')->get();
foreach($heads as $head){
print_r($head->project_owner_id);
print_r($head->user_id);
}
The below query fetched project owner id and user_id.How to push the value in role_mapping table
Try to refer to this one, using Attach, Detach in laravel : http://kaloraat.com/questions/laravel-attach-detach-and-sync-methods
Hope this helps :)
Like this way
Assuming your model name as MappingTable
foreach($heads as $head){
$mapTable = new MappingTable();
$mapTable->user_id = $head->user_id;
$mapTable->role_id = $head->project_owner_id;
$mapTable->save();
}
OR alternatively you can pass $data array like this
$data = array(
array('user_id'=>$head->user_id, 'role_id'=> ),
array('user_id'=>$head->user_id, 'role_id'=> $head->project_owner_id),
//...
);
MappingTable::insert($data); // Eloquent
DB::table('role_mapping table')->insert($data); // Query Builder

subquery in andFilterWhere in yii2

I have to execute this query
select count(id) as numberofcompanies, sum(offered_value) as total_offered_value from campaign_comapany
where ( campaign_id in (select id from campaing where user_id = current_user ) or campaing_company.sp_user_id = current_user)
and campaign_company.status = '3'
And I wrote the query like this in yii2-
$query->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value'])
->from('campaign_company')
->andFilterWhere(['or',['in','campaign_id',(new yii\db\Query())->select(['id'])->from('campaign')->where(['=','user_id',Yii::$app->user->id])],['=','campaign_company.sp_user_id',Yii::$app->user->id]])
->andWhere(['=','status','3'])
->one();
But it gives me error with unknow column campaign_company.user_id
but working if I just use where like following-
$query->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value'])
->from('campaign_company')
->where(['in','campaign_id',(new yii\db\Query())->select(['id'])->from('campaign')->where(['=','user_id',Yii::$app->user->id])])
->andWhere(['=','status','3'])
->one();
What should I do to get the result mentioned sql query, I don't want to hit database server two time, thanks in advance
Use join:
$query->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value'])
->from('campaign_company')
->innerJoin('campaign','`campaign`.`id` = `campaign_company`.`campaign_id`')
->where([
['=','campaign.user_id',Yii::$app->user->id])],
['=','campaign.campaign_company.sp_user_id',Yii::$app->user->id],
['=','campaign_company.status','3']
]
->one();
As is it is difficult to follow your logic. To simplify your code and your query, add the first condition as plain sql. Also since the second condition is required, you can swap the positions as follows:
$query
->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value'])
->from('campaign_company')
->where(['status' => '3'])
->andWhere(['
campaign_id in (select id from campaign where user_id = :current_user )
or campaign_company.sp_user_id = :current_user1',
[':current_user' => Yii::$app->user->id, ':current_user1' => Yii::$app->user->id]])
->one();

Can't retrieve records using foreign key on the same table in Laravel 5.2

I'm using Laravel 5.2 to retrieve records from a database.
My table (simplified):
services:
id
name
parent_id
parent_id is FK to the same table (FK to services.id).
This code returns an empty collection:
$category->services->where( 'parent_id', 0 )
Select with other where condition works properly. ex.
$category->services->where( 'name', 'foo )
returns not empty results.
Raw SQL works fine too:
SELECT * FROM services WHERE parent_id = 0;
What is wrong with Eloquent or how to use it in a way where I can retrieve records with concrete parent_id ?
Your query should be like this:
$services = $category->services()->where('parent_id', 0)->get()

Column Name Conflict on Laravel 4 Fluent Query Builder

I have a query like this:
$users = DB::table('users')->join('user_roles','users.role_id','=','user_roles.id')->get();
and a table that has a column id (users.id) and another table that has columns id and user_id (user_roles.id & user_roles.user_id),
but the problem is.. what is being returned on $user->id is the user_roles.id instead of the users.id column.. how do i fix this so that what i get is not the role id but the user id instead..
thanks!
Found it!
using ->select('users.*', 'user_roles.role_name') i was able to remove user_roles.id from the returned values and thus eliminating the conflict.
Here is the final query:
$users = DB::table('users')->join('user_roles','users.role_id','=','user_roles.id')->select('users.*', 'user_roles.role_name')->get();
The better way to do this is using 'as':
$users = DB::table('users')->join('user_roles','users.role_id','=','user_roles.id')->get(array('users.*', '**user_roles.id as user_roles_id**', 'user_roles.*'));

Categories