Problem with populating database column with seeding in Laravel - php

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,
]);

Related

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

Using same id for multiple rows using codeigniter

I have a table with three fields
id (primary key / auto incremented)
product_name
group_id
my problem is when i insert multiple rows through form the whole group of rows should get same groupId & it should be incremented by 1 at the time of submission as there can be many users submitting the form at the same time. I dont know how to do it. Please help.
my model
function get_last_group_id() {
$this->db->select('group_id');
$this->db->from('mytable');
$this->db->order_by('group_id', 'DESC');
$this->db->limit('1');
$query = $this->db->get();
return $query->result();
}
function save_rows($ids,$product_names,$group_ids){
$this->db->trans_begin();
$ndx=0;
foreach($ids as $id){
$data = array(
'id' => $id,
'product_name' => $product_names[$ndx],
'group_id' =>$group_ids[$ndx],
$this->db->insert("product_details",$data);
$this->db->update($this->table);
$ndx++;
}
There is no need to make seperate function for getting group id and set id field also if that is auto incre
function save_rows($ids,$product_names){
$this->db->trans_begin();
$ndx=0;
$group_id = $this->db->select("MAX(group_id) as group_id")
->from("mytable")
->get()->row_array();
foreach($ids as $id){
$data = array(
'product_name' => $product_names[$ndx],
'group_id' =>$group_id['group_id']+1,
);
$this->db->insert("product_details",$data);
$ndx++;
}
You can create a new table say 'groups'
fields: id(Auto Increment) and group_name (varchar)
generate group name randomly.
Then before inserting products create a new group then you will get a new groupID that will be unique.
Then using that groupID you can carry your option forward

How to get the last insert ids from laravel 4

I am using laravel 4. I have a table called documents. I am inserting data in the Document table using Document::insert() function.
My code is given below
$statuses = array();
foreach($content as $i){
array_push($statuses, array(
'user_id' => $user->id,
'document' => $i->text
));
}
$users = Document::insert($statuses);
Now I want to get the insert ids. But the $users variable only gives me a boolean variable called true. How can I get the insert ids.
Use insertGetId()
If the table has an auto-incrementing id, use insertGetId to insert a
record and retrieve the id
Code Snippet
$id = DB::table('Document')->insertGetId($yourarray);
Note: When using PostgreSQL the insertGetId method expects the
auto-incrementing column to be named "id".

Laravel 4 Eloquent returns wrong ID

I have 3 tables in my database:
Campaigns
Users
Companies
One company may have some users. One user may have some campaigns. A user (with admin rights) can do some actions with any campaign that belongs to his company. So, I want to check whether
he's doing these actions with his campaign or not (in the last case I return something like "access denied").
My condition
Campaign::join('users', 'users.id', '=', 'campaigns.user_id')
->where('users.company_id', '=', Auth::user()->company->id)
->where('campaigns.id', '=', Input::get('id'))
->first();
So if I got unique campaign - it's ok, if I got null - something's wrong and I send "access denied" to user as he's dealing with other company campaign.
This code produces next query:
array(3) {
["query"]=>
string(148) "select * from `campaigns` inner join `users` on `users`.`id` = `campaigns`.`user_id` where `users`.`company_id` = ? and `campaigns`.`id` = ? limit 1"
["bindings"]=>
array(2) {
[0]=>
string(1) "2"
[1]=>
string(2) "13"
}
["time"]=>
float(0.42)
}
Using phpmyadmin I tried the same query and got a campaign with ID = 13.
But when I was debugging my application I found out that
dd($campaign->id);
returns 8 instead. 8 also equals campaigns.user_id (The record has both campaigns.id and campaigns.user_id = 8).
I can't figure out why it's happening. Even if something wrong with my SQL query (what I doubt as phpmyadmin returned right results), I got where condition campaigns.id = Input::get('id'), where Input::get('id') = 13. Why id is being changed?
Of course I can do this security check in two steps, like first get the campaign, then check
$campaign->user->company->id = Auth::user()->company->id but just wondering ...
If you run this query in phpMyAdmin you should probably be able to see that the result contains multiple columns by the name "id". When PHP parses the query result to an associative array or object, keys must be unique! If keys are colliding, the last column will be used!
Example:
SQL result:
id user_id name id name company_id
1 2 Camp1 2 Pelle 1
PHP result:
array (size=1)
0 =>
object(stdClass)[131]
public 'id' => string '2' (length=1)
public 'user_id' => string '2' (length=1)
public 'name' => string 'Pelle' (length=5)
public 'company_id' => string '1' (length=1)
To solve this you could add a select clause to only select the campaign columns:
Campaign::select('campaigns.*')
->join('users', 'users.id', '=', 'campaigns.user_id')
->where('users.company_id', '=', Auth::user()->company->id)
->where('campaigns.id', '=', Input::get('id'))
->first();
This seems like a limitation in the Eloquent library. Instead of using the last "id", it should be more proactive in searching for the "id" of the main table of the query. Or use "as" in the SQL statements.
Another solution would be to name each table's id field uniquely. e.g. user.user_id, campaigns.campaign_id. This would collide with the foreign keys in other tables, so name foreign keys as campaigns.user_fid.
If you want control over the actual table who's duplicate column is used, just add the tables to an array in a specific order. The last one will be the ->id property.
->select([
'table1.*',
'table2.*',
'tags.*',
'companies.*',
'users.*',
])
This way you preserve all unique columns that are selected with the join.
Should you want specific columns from a specific table you can use an AS:
->select([
'table1.*',
'table2.*',
'tags.*',
'companies.*',
'users.*',
'table1.id AS table1_id',
'tags.name AS tag_name',
'companies.name AS company_name',
])

Kohana 3 ORM: How to get data from pivot table? and all other tables for that matter

I am trying to use ORM to access data stored, in three mysql tables 'users', 'items', and a pivot table for the many-many relationship: 'user_item'
I followed the guidance from Kohana 3.0.x ORM: Read additional columns in pivot tables
and tried
$user = ORM::factory('user',1);
$user->items->find_all();
$user_item = ORM::factory('user_item', array('user_id' => $user, 'item_id' => $user->items));
if ($user_item->loaded()) {
foreach ($user_item as $pivot) {
print_r($pivot);
}
}
But I get the SQL error:
"Unknown column 'user_item.id' in
'order clause' [ SELECT user_item.*
FROM user_item WHERE user_id = '1'
AND item_id = '' ORDER BY
user_item.id ASC LIMIT 1 ]"
Which is clearly erroneous because Kohana is trying to order the elements by a column which doesn't exist: user_item.id. This id doesnt exist because the primary keys of this pivot table are the foreign keys of the two other tables, 'users' and 'items'.
Trying to use:
$user_item = ORM::factory('user_item', array('user_id' => $user, 'item_id' => $user->items))
->order_by('item_id', 'ASC');
Makes no difference, as it seems the order_by() or any sql queries are ignored if the second argument of the factory is given.
Another obvious error with that query is that the item_id = '', when it should contain all the elements.
So my question is how can I get access to the data stored in the pivot table, and actually how can I get access to the all items held by a particular user as I even had problems with that?
Thanks
By default, all of Kohana's ORM models expect the table's primary key to be 'id.' You need to set $_primary_key in your model to something else.
$user_item = ORM::factory('user_item', array('user_id' => $user, 'item_id' => $user->items));
I think you need to provide a single item_id value for this to work, not an array of objects.
Also, to find all entries for a single user you should be able to do this:
$user_items = ORM::factory('user_item', array('user_id' => $user));
Does that answer your question?

Categories