Hello I'm trying to replicate this SQL code into Laravel qBuilder but I'm not getting the result I want in the collection:
select chars.name, class.name, specs.name
FROM characters as chars
JOIN charclasses as class
JOIN charspecs as specs
WHERE chars.class_id = class.id
AND chars.spec_id = specs.id
I get the following output:
Then I tried this in Laravel:
$charData = DB::table('characters')
->select('characters.*', 'charclasses.name', 'charspecs.name')
->join('charclasses', 'characters.class_id', '=', 'charclasses.id')
->join('charspecs', 'characters.spec_id', '=', 'charspecs.id')
->orderBy('user_id', 'ASC')
->get();
dd($charData);
and the result is:
The problem is that you are selecting three fields with the same name. These fields are added to an array in the php code, but the array field is being overwritten twice because there can be no duplicate keys in an associative array. If you want to select the three names you will have to give them another name.
$charData = DB::table('characters')
->select('characters.*', 'charclasses.name as charclassname', 'charspecs.name as charspecname')
->join('charclasses', 'characters.class_id', '=', 'charclasses.id')
->join('charspecs', 'characters.spec_id', '=', 'charspecs.id')
->orderBy('user_id', 'ASC')
->get();
dd($charData);
Related
I have a base table called inventory_base and several other related tables having foreign key at inventory_base. I want to fetch data from all the tables by id present on inventory_base using Laravel Eloquent (Laravel 8)
I wrote the following query
$where = ['base_inventory.id' => (int)$request->id];
$data = BaseInventory::select(
"base_inventory.id as id",
"base_inventory.spare_id as spare_id",
"base_inventory.item_type as item_type",
"base_inventory.area as area",
"base_inventory.machine_name as machine_id",
"base_inventory.item_category as item_category",
"base_inventory.item_desc as item_desc",
"base_inventory.location as location",
"base_inventory.spare_category as spare_category",
"base_inventory.unit as unit",
"base_inventory.max_stock_level as max_stock_level",
"base_inventory.reorder_level as reorder_level",
"base_inventory.opening_balance as opening_balance",
"base_inventory.old_id as old_id",
"base_inventory.unit_price as unit price",
"base_inventory.created_by as created by",
"base_inventory.updated_by as updated_by",
"item_type_base.item_type as item_type_name",
"area_base.area as area_name",
"machine_base.machine_name as machine_name",
"item_category_base.category as item_category_name",
"base_inventory.item_desc as item_desc",
"location_base.location as location_name",
"spare_category.spare_category as spare_category_name",
"unit_base.unit as unit_name",
"base_inventory.max_stock_level as max_stock_level",
"base_inventory.reorder_level as reorder_level",
"base_inventory.opening_balance as opening_balance",
"base_inventory.old_id as old_id",
"base_inventory.unit_price as unit price",
"users.name as created_by"
)
->join('item_type_base', 'item_type_base.id', '=', 'base_inventory.item_type')
->join('area_base', 'area_base.id', '=', 'base_inventory.area')
->join('machine_base', 'machine_base.id', '=', 'base_inventory.machine_name')
->join('item_category_base', 'item_category_base.id', '=', 'base_inventory.item_category')
->join('location_base', 'location_base.id', '=', 'base_inventory.location')
->join('spare_category', 'spare_category.id', '=', 'base_inventory.spare_category')
->join('unit_base', 'unit_base.id', '=', 'base_inventory.unit')
->join('users', 'users.id', '=', 'base_inventory.created_by')
->where($where)
->get();
If I execute it it returns no rows. But if i run it without where clauses then it returns matching rows.
I tried printing raw query using ->toSql(). It shows where (base_inventory.id = ?) at the end. Printing $request->id displays the passed id without any error. What I am missing? Please help me to find it out. Thanks in advance
its there's a way to optimize this code. I already google it but I don't know what the exact keyword to search, so I always failed to find the answer.
At this code I get the Approver List of ID 512 (requestor)
$approver_list = DB::table('users')
->leftjoin('approver_group_list', 'approver_group_list.user_id', '=', 'users.id')
->leftjoin('approval_roles', 'approval_roles.as_id', '=', 'approver_group_list.as_id')
->leftjoin('approver_requestor_list', 'approver_requestor_list.at_id', '=', 'approval_roles.at_id')
->where('approver_requestor_list.user_id', 512)
->get();
Then I use array_push to extract the data of approver_list, then I use the value of $result to get value in LeaveMain table.
$result = array();
foreach($approver_list as $al)
{
array_push($result , $al->user_id);
}
$leave_list = LeaveMain::whereIn('requestor_id', $result)->get();
My problem is, it is always need to use array_push to to extract data, or laravel have a way to optimize this code.
$approver_list = DB::table('users')
->leftjoin('approver_group_list', 'approver_group_list.user_id', '=', 'users.id')
->leftjoin('approval_roles', 'approval_roles.as_id', '=', 'approver_group_list.as_id')
->leftjoin('approver_requestor_list', 'approver_requestor_list.at_id', '=', 'approval_roles.at_id')
->where('approver_requestor_list.user_id', 512)
->pluck('id');
$leave_list = LeaveMain::whereIn('requestor_id', $approver_list)->get();
Basically you can pluck the id from the table itself, rather than fetching all the data and then taking the id later, and whereIn accepts collection as the second argument. so no need to cast to an array
The whereIn method filters the collection by a given key / value
contained within the given array: Link
You don't need to loop the approver_list values, you can use pluck method to retrieves all of the values for user_id.
$result = $approver_list->pluck('user_id')->toArray();
$leave_list = LeaveMain::whereIn('requestor_id', $result)->get();
Objective
I'm trying to select some columns from a multiple inner join query.
I have a model called Item and this model belongs to the other three Produto, Unidadeand Marca
Problem
I'm not getting the full result declared on my query. Only some columns are being shown.
What I tried
I have already tried to put everything in one ->select() , but I had the same issue. I've checked the relations configuration is working in other part of the code
Result Obtained
Only the columns from first and the last addSelect() are being shown.
var_dump() output
Code
public function download()
{
$item = new Item;
// $data = $item->query()
$data = DB::table('items')
->join('produtos', 'items.produto_id', '=', 'produtos.id')
->join('unidades', 'items.unidade_id', '=', 'unidades.id')
->join('marcas', 'items.marca_id', '=', 'marcas.id')
->select('items.codigo','items.nome')
->addSelect('items.metrica_cod', 'items.metrica')
->addSelect('produtos.codigo', 'produtos.nome')
->addSelect('unidades.codigo', 'unidades.nome')
->addSelect('marcas.codigo', 'marcas.nome')
->get();
var_dump($data);
}
I want to get the template from user_webhook table in my database.In WHERE condition i am checking user_id,app_id and if either notify_admin or notify_customer value is 1 in user_webhook table.I am using query..
$templates= $this->where('notify_admin',1)
->orwhere('notify_customer',1)
->where('user_webhooks.user_id',$user_id)
->where('user_webhooks.app_id',$app_id)
->select( 'webhooks.id as webhook_id','webhooks.app_id','webhooks.topic','webhooks.type','webhooks.action',
'webhooks.sms_template','user_webhooks.id','user_webhooks.notify_admin',
'user_webhooks.notify_customer','user_webhooks.user_id','user_webhooks.sms_template_status',
'user_webhooks.sms_template as sms'
)
->join ('webhooks',function($join){
$join>on('webhooks.id','=','user_webhooks.webhook_id');
})
->get()
->toArray();
when i get query using DB::getQueryLog(), I found the query seems Like
select `telhok_webhooks`.`id` as `webhook_id`, `telhok_webhooks`.`app_id`,
`telhok_webhooks`.`topic`, `telhok_webhooks`.`type`, `telhok_webhooks`.`action`,
`telhok_webhooks`.`sms_template`, `telhok_user_webhooks`.`id`,
`telhok_user_webhooks`.`notify_admin`, `telhok_user_webhooks`.`notify_customer`,
`telhok_user_webhooks`.`user_id`, `telhok_user_webhooks`.`sms_template_status`,
`telhok_user_webhooks`.`sms_template` as `sms` from `telhok_user_webhooks`
inner join
`telhok_webhooks` on `telhok_webhooks`.`id` = `telhok_user_webhooks`.`webhook_id`
where `notify_admin` = ? or `notify_customer` = ? and `telhok_user_webhooks`.`user_id`
= ? and `telhok_user_webhooks`.`app_id` = ?
The result of query giving result of all app_id and user_id.
So Please tell me use of OR in where condition.
Thanks in advance.
You may chain where constraints together as well as add or clauses to the query. The orWhere method accepts the same arguments as the where method:
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere('name', 'John')
->get();
Advanced usage:
Usere::where('id', 46)
->where('id', 2)
->where(function($q) {
$q->where('Cab', 2)
->orWhere('Cab', 4);
})
->get();
The whereIn method verifies that a given column's value is contained within the given array:
$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();
More: https://laravel.com/docs/5.5/queries
Change
->where('notify_admin',1)
->orwhere('notify_customer',1)
to
->where(function($q){
$q->where('notify_admin',1)
->orWhere('notify_customer',1);
})
Without this, the orWhere will compare to all other wheres in your query instead of just comparing those two columns
I am trying to get a result set from a laravel eloquent query whereby I match a column against a list of values in an array.
$authenticated_operation_ids = AccessControl::where('user_id', '=', $user_id)
->where('entity_type_id', '=', $operation_entity_id)
->pluck('entity_access_id')->toArray();
$authenticated_operations = Operation::whereIn('id', $authenticated_operation_ids);
return view('page.index')->withOperations($authenticated_operations);
You can try it as:
$authenticated_operation_ids = AccessControl::where('user_id', '=', $user_id)->where('entity_type_id', '=', $operation_entity_id)->pluck('entity_access_id')->toArray();
$authenticated_operations = Operation::whereIn('id', $authenticated_operation_ids)->get();
return view('page.index')->withOperations($authenticated_operations);
Add get() at the end of the query.
1) pluck returns a single value from a single row. You want lists to get a single column from multiple rows. toArray may not be needed, as it returns an array of values
$authenticated_operation_ids = AccessControl::where('user_id', '=', $user_id)
->where('entity_type_id', '=', $operation_entity_id)
->lists('entity_access_id');
2) You're forgetting to actually retrieve the rows in your second line:
$authenticated_operations = Operation::whereIn('id', $authenticated_operation_ids)
->get();
You have to call get() function on the result set to obtain results. The modified code will be like
$authenticated_operation_ids = AccessControl::where('user_id', '=', $user_id)->where('entity_type_id', '=', $operation_entity_id)->get()->pluck('entity_access_id');
$authenticated_operations = Operation::whereIn('id', $authenticated_operation_ids)->get();
return view('page.index')->withOperations($authenticated_operations);
or you can use a cursor to process it.