Laravel whereHas not filtering as expected - laravel

The 2 models involved are JobRequest and StationJob. Really their relationship is oneToMany. I have a relationship set up for this $jobRequest->stationJobs().
Further to this I need a hasOne relationship latestStation, based on the same model. I need this relationship to filter my collection of JobRequests based on whether the JobRequest has a latestStation equal to a specified station.
I am expecting to get an empty list of JobRequests because I know the latestStation is equal to id 3 and I am filtering for id 2. Instead I get the jobRequest, with latestStation id 3 even though I am filtering for 2.
Relationship
public function latestStationTest()
{
return $this->hasOne(StationJob::class)->whereNotNull('finished')->latest();
}
Controller
$stationId = $request->station_id;
$jobRequests = JobRequest::with(['latestStationTest'])->whereHas('latestStationTest', function($query) use ($stationId) {
$query->where('station_id', $stationId);
})->get();
Query Result
[2020-10-17 07:39:07] local.INFO: array (
0 =>
array (
'query' => 'select * from `job_requests` where exists (select * from `station_jobs` where `job_requests`.`id` = `station_jobs`.`job_request_id` and `station_id` = ? and `finished` is not null)',
'bindings' =>
array (
0 => 2,
),
'time' => 1.0,
),
1 =>
array (
'query' => 'select * from `station_jobs` where `finished` is not null and `station_jobs`.`job_request_id` in (1) order by `created_at` desc',
'bindings' =>
array (
),
'time' => 0.5,
),
)
I've tried...
Switching with() before or after whereHas makes no difference.
adding ->where() to with() selects the StationJob with the specified id, instead of checking if the latestStation id is equal to the specified id.

Related

find_in_set with join in laravel

How to get the desire output using laravel query. Tried that way does not get success please guide thanks a lot in advance
Is there any way we can set it in model if possible please guide
User
id name b_id
1 Alax 1,3
2 Rex 2,4
3 Lex 2,3
Books
id book_name book_author
1 Javascript jim
2 PHP json
3 LARAVEL rax
4 SYMPHONY Alax
Output
id name b_id
1 Alax Javascript, LARAVEL
2 Rex PHP, SYMPHONY
3 Lex PHP, LARAVEL
And Query:
$res = DB::table('user')->leftJoin('book', function($join){
$join->on(DB::raw("find_in_set(book.id, user.b_id)",DB::raw(''),DB::raw('')));
});
Try this.
$data = \DB::table("user")
->select("user.*",\DB::raw("GROUP_CONCAT(book.book_name) as book_name"))
->leftjoin("book",\DB::raw("FIND_IN_SET(book.id,user.b_id)"),">",\DB::raw("'0'"))
->get();
\DB::raw("GROUP_CONCAT(CONCAT(book.book_name, ' - ', book.book_author) SEPARATOR ', ') AS book_name_author")
Your output looks like.
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Alax
[b_id] => 1,3
[book_name] => Javascript,LARAVEL
)
[1] => stdClass Object
(
[id] => 2
[name] => Rex
[b_id] => 2,4
[book_name] => PHP,SYMPHONY
)
[2] => stdClass Object
(
[id] => 3
[name] => Lex
[b_id] => 2,3
[book_name] => PHP,LARAVEL
)
)
)
I don't know the exact Laravel syntax problem you are currently facing, but there is a potential problem with your current left join logic. If a given user have more than one matching book, then he would appear in the result set one time for each match. This presumably is not what you want, so I would suggest joining using EXISTS logic:
SELECT u.id, u.name
FROM User u
WHERE EXISTS (SELECT 1 FROM Books b WHERE FIND_IN_SET(b.id, u.b_id) > 0);
The Laravel code:
$res = DB::table('user u')
->whereExists(function ($query) {
$query->select(DB::raw(1))
->from('book b')
->whereRaw('FIND_IN_SET(b.id, u.b_id) > 0');
})
->get();
The exists approach ensures that each user would only appear once in the result set.

Inserting multipe rows from dynamic form fields using laravel 5

How can I store multiple form array data in laravel, as I need to create a new record against each array index.
[0] => Array
(
[make] => test
[model] => XYZ
)
[1] => Array
(
[make] => s4
[model] => BB
)
[2] => Array
(
[make] => 99
[model] => AX
)
This is what I am trying to, but here loop get executed 6 times instead of three
$results = $request->all();
foreach ($results as $key => $value) {
echo $key;
// insert operation
}
I believe you should specify the control/field because the Request contains other (non-data) information. Something like:
$results = $request['array_name'];
https://laravel.com/docs/5.4/queries#inserts
Model::insert($request->all())
This will mass insert each array into your database. insert do not automatically set datetime values for created_at and updated_at, note that the array keys should match your table columns, and make sure your model has these fields as $fillables.

How to insert the array values in database using for each loop

I have array i want insert into the values in database using codeigniter, i don't know how to insert , i trying but i am not able to get the answer
My model
print_r($subjectHandling);
Array
(
[subjectId] => Array
(
[0] => 1
[1] => 2
)
)
now i want insert the values in database in this values.
I am trying like this
foreach($subjectHandling as $key=>$value) {
$reg_dat = array(
'statffId' => '1',
'subjectId' => $value,
);
$this->db->insert("subject_handling" , $reg_dat);
}
I m getting error ** Array to string conversion** , so how do this. i want to insert two roes in databse
This should work
$subjectHandling['subjectId'] = array(1, 2);
$reg_dat = array();
foreach($subjectHandling['subjectId'] as $key => $value) {
$reg_dat[] = array('staffId'=> 1, 'subjectId' => $value);
}
$this->db->insert_batch('subject_handling', $reg_dat);
https://www.codeigniter.com/userguide3/database/query_builder.html#inserting-data

codeigniter form_validation is_unique compare data between tables

I have a from which lists several items that can be selected by check box and a dropdown permitter added. In a separate part of the form is have another check box. This is submitted as two arrays.
The arrays look like this
Array
(
[1] => Array
(
[num_copy] => 1
[dwg_rev] => B
[dwg_id] => 1
)
[2] => Array
(
[num_copy] => 1
[dwg_rev] => B
[dwg_id] => 2
)
)
Array
(
[1] => Array
(
[client_id] => 1
)
)
I need to pass these two arrays to a form_validation that can check is dwg_rev has already been added to the database for the selected client_id.
I tried to use is_unique, but it can only check in one table to see if this already exists in it.
This is what my form validation currently looks like
$rows = array();
if(!empty($_POST['result']))
{
$rows = $_POST['result'];
$temp_dwg_array = array_column($rows, 'temp_dwg_id');
foreach($temp_dwg_array as $key => $temp_dwg_id)
{
$this->form_validation->set_rules('result['.$temp_dwg_id.'][dwg_rev]', 'Revision' , 'required|callback_check_issued_rev');
}
} else $this->form_validation->set_rules('result[][temp_dwg_rev]', 'Revision' , 'required');
if(!empty($_POST['client']))
{
$temp_client_array = array_column($_POST['client'],'client_id');
foreach($temp_client_array as $key => $client_id)
{
$this->form_validation->set_rules('client['.$client_id.'][client_id]', 'Please make a selection from the distribution list' , 'required|callback_check_issued_rev');
}
}
else $this->form_validation->set_rules('client[][client_id]', 'Distribution' , 'required');
I want to create a callback function, but I can't figure out how to pass two variables to the callback function to compare to the db.

Joomla user management

I got a Joomla ticketing module, that displays at a certain part of the page, the current tickets of the current user. I want to create user groups, in which the group members can view all of the tickets belongin to that group. I thought the easiest way is to create Joomla groups, assign the users to those, and to when a user loges in, it can see all of the tickets in its group. I added my code to the start of the function, but something is wrong... For every user (currently the "Registered" ones) displays the same result, that of the last users tickets, and I don't know why: Here is the code:
function gTickets()
{
$user =& JFactory::getUser();
$user_id = (int) $user->get('id');
//get user_group_id from db based on current users id
{...}
//get all users with that user_group_id
$db1->setQuery($db1->getQuery(true)
->select('*')
->from("#__user_usergroup_map")
->where("group_id = '$groupss'")
);
$groupss1=$db1->loadRowList();
$return1=array();
// for every user_id
foreach ($groupss1 as $keya)
{
$user_id = $keya[0]; // the id of users
$where = "";
if ($this->is_staff)
$where .= " AND t.`staff_id`='".$user_id."'";
else
$where .= " AND t.`customer_id`='".$user_id."'";
$tickets = $this->_getList(
"SELECT t.id, t.subject, t.last_reply_customer, s.name AS status_name FROM
#__rsticketspro_tickets t LEFT JOIN #__rsticketspro_statuses s ON
(t.status_id=s.id) WHERE 1 $where ORDER BY `last_reply` DESC", 0,
$this->params->get('tickets_limit', 3));
print_r($tickets);
return $tickets;
}
I got some questions, that I didn't know how to seach for...
what is the letter dot fieldname in the sql query? eg:
SELECT m.ticket_id, m.message FROM #__ticket_messages m WHERE m.user_id !='".$user_id."
what does the "m" mean before the WHERE?
what does the "1" do here: WHERE 1 $where
Also, I looked in the ACL managers, but could not make it work with this code.
Edit: Thanks for the fast answers! I got 1 more, and I think it's an easy one, but I can't get it to work...
If I print the content of the $ticket array into another array, I get an array with multiple arrays. That is why my code is not working... The array i'm getting is:
Array (
[0] => stdClass Object (
[id] => 1
[subject] => use1
[last_reply_customer] => 1
[status_name] => open
)
)
Array (
[0] => stdClass Object (
[id] => 3
[subject] => use2
[last_reply_customer] => 1
[status_name] => open
)
[1] => stdClass Object (
[id] => 2
[subject] => use2
[last_reply_customer] => 1
[status_name] => open
)
)
I would like the array to look like this:
Array (
[0] => stdClass Object (
[id] => 1
[subject] => use1
[last_reply_customer] => 1
[status_name] => open
)
[1] => stdClass Object (
[id] => 3
[subject] => use2
[last_reply_customer] => 1
[status_name] => open
)
[2] => stdClass Object (
[id] => 2
[subject] => use2
[last_reply_customer] => 1
[status_name] => open
)
)
Thanks!
Edit: is all of this complicated to achieve?
Look into ACL to get that part working, but to answer the 3 questions you posted at the bottom of your question:
1) the letter.field_name in the query represents the table alias.field_name in the query. The alias (m) makes it easier so you don't have to keep typing the full table name each time.
2) The m before the WHERE is actually setting the table alias, but with lazy syntax. It should say:
SELECT m.ticket_id, m.message FROM #__ticket_messages AS m
3) The "WHERE 1" is the SQL way of saying "if (true)". Since they are immediately appending the $where clause afterwards "WHERE 1 $where", the resulting query looks like this:
WHERE 1 AND t.staff_id = '" . $user_id . "'
Did you code this originally? or is it a component that you picked up somewhere? It should be using the query builder instead of direct SQL like it currently is, to make it more portable and more clear as to what it is doing.

Resources