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
Related
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,
]);
I have many to many relationship. In postman I pass find_id and status.
My query is like: UPDATE finds_user SET status = TRUE WHERE find_id = 2 AND user_id = 1.
I do it now like that:
DB::table('finds_user')
->where('find_id', '=', $request->find_id)
->where('user_id', '=', $user->id)
->update(['status' => $request->status]);
How I can do it with Eloquent instead of DB Query Builder?
Thank you a lot!
we have tow condition for update:
1- find_id = 2
2- user_id = 1.
suppose the relation name in the user model called 'finds'
the query will look like this:
User::find(1)->finds()->newPivotQuery()->where('find_id',2)->update(['status'=>true])
and if you have a model for the pivot table with name like "FindUser":
FindUser::where('user_id',$user->id)->where('find_id',2)->update(['status'=>true]);
I want to fetch results from two tables properties and properties_x where properties.address or properties_x.address_x like test with laravel pagination.
There is no foreign key relationship between these two tables.
properties
id name address
1 test1
2 test2
3 test3
4 test3 test
5 test4 test
properties_x
id name address
1 test1_x test
2 test2_x
3 test3_x
4 test3_x test
5 test4_x
Expected results:
name address
test3 test
test4 test
test1_x test
test3_x test
Use union all to union two table's datas,
And get the columns from these datas in DB, so you can use pagination.
try it like this:
$p1 = DB::table('properties')
->where('address', 'test')
->select('name', 'address');
$p2 = DB::table('properties_x')
->where('address', 'test')
->select('name', 'address');
$p = $p1->unionAll($p2);
DB::table(DB::raw("({$p->toSql()}) AS p"))
->mergeBindings($p)
->select('name', 'address')
->paginate(10);
I don't know if there is another way, but it works for me well
$res= [];
$tableONe = Property::where('address','test')->get();
array_push($res,$tableOne);
$tableTwo = PropertyX::where('address','test')->get();
array_push($res,$tableTwo);
now $res have both data table together
union all then laravel query builder provide unionAll method for mysql union. when you are doing big project or ERP level project then mostly you require to use union for getting data from database with multiple table. In Following example you can see how to use union all in Laravel 5.
Example:
$silver = DB::table("product_silver")
->select("product_silver.name"
,"product_silver.price"
,"product_silver.quantity");
$gold = DB::table("product_gold")
->select("product_gold.name"
,"product_gold.price"
,"product_gold.quantity")
->unionAll($silver)
->get();
print_r($gold);
$users = User::select('id','name')
->where('name','LIKE','%'.$key.'%');
$properties = Property::select('id','name')
->where('name','LIKE','%'.$key.'%');
$results = Program::select('id','name')
->where('name','LIKE','%'.$key.'%') ->union($users)
->union($properties)
->simplePaginate();
In my application, there's two tables at the moment: users and employees. The latter is simply a profile table for the boilerplate users table that ships with Laravel.
I have two foreign keys inside of employees, one is user_id that points to id on users table. So basically, the profile data of the registered user. The second foreign key in employees is manager_id. That is the id of the person who is the manager of an employee. Some users are managers and have a blank manager_id field.
I want to retrieve the row from my Employee model where the user_id matches the manager_idand then send them all to my view, where they will see the first_name and last_name of the manager. At the moment I see the manager ID instead of their name.
Sample LeftJoin =>
DB::connection('testing')->table('table1 as t1')
->select('t1.column, t2.column')
->leftJoin('table2 as t2','t2.client_id','=','t1.id')
->get();
Try some thing like this:
$users = DB::table('users t1')
->join('users t2', 't1.id', '=', 't2.user_id')
->select('your column list')
->get();
// here we are creating 2 aliases for users table which make it self join
In your Employees model add the following method:
public function manager()
{
return $this->hasOne('App\User', 'id', 'manager_id');
}
You can then get the name of the Manager like this:
$employee = \App\Employee::find(1);
$manager = $employee->manager()->first();
$manager_name = $manager->name;
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