I'm working on a table which should show clients which have active jobs. I've got a page with all clients and this is working. I'm trying to get a query which is conditional on the client having active jobs. So here is what I have in my dataSource function:
public function dataSourcejobs(Request $request) {
$search = $request->query('search', array('value' => '', 'regex' => false));
$draw = $request->query('draw', 0);
$start = $request->query('start', 0);
$length = $request->query('length', 25);
$order = $request->query('order', array(0, 'desc'));
$filter = $search['value'];
$sortColumns = array(
0 => 'id',
1 => 'client',
2 => 'active_jobs',
3 => 'is_enabled',
4 => 'actions'
);
$query = Client::select( 'clients.*' );
if (!empty($filter)) {
$query->where( 'title', 'like', '%'.$filter.'%' );
}
$recordsTotal = $query->count();
$sortColumnName = $sortColumns[$order[0]['column']];
$query->orderBy($sortColumnName, $order[0]['dir'])
->take($length)
->skip($start);
$json = array(
'draw' => $draw,
'recordsTotal' => $recordsTotal,
'recordsFiltered' => $recordsTotal,
'data' => [],
);
$clients = $query->get();
foreach ($clients as $client) {
// Get active jobs for this client.
$jobs = Job::where( 'client_id', $client->id )->where('is_active', 1)->get();
$json['data'][] = [
$client->id,
$client->title,
'<button class="jobs">' . count($jobs) . ' Jobs</button>',
( $client->is_enabled === 1 ) ? 'Yes' : 'No',
'' . config( 'ecl.EDIT' ) . ' ' . config( 'ecl.WORK' ) . ''
];
}
return $json;
}
I've tried to do things like $query = Client::select( 'clients.*' )->count($client->jobs); but this is obviously wrong and errors. I also tried to do this in the loop (by checking the count) but this obvoiusly broke how the pagination works (but did show only clients with active jobs)
I should point out that the function above shown all clients even the ones which have no associated active jobs.
thanks
to get the count along with each client you can use withCount refer to this link https://laravel.com/docs/9.x/eloquent-relationships#counting-related-models
like the following
$query = Client::withCount('jobs');
as for getting the clients who only have jobs you can use whereHas
Related
In view, there's 2 tables and implemented the pagination for both but having a problem in the buttons
When we tried to change the page of table 1, the table 2 is also changed
In the controller, there's 4 model: 1) Purchase; 2) Direct Payments; 3) Sales; 4) Direct Collections.
purchases columns
id
number,
date_delivered
direct payments columns
id,
number
date
After getting the data from the perspective model we, rearrange the format
**Rearrange the format **
public function setToInputOutputTax($data,$module,$module_id)
{
$items = [];
foreach($data as $d => $datum) {
$items[] = [
'id' => $datum->id,
'checkbox' => 0,
// 'vat_type' => $vat_type,
'transaction_date' => isset($datum->date_delivered) ? $datum->date_delivered : $datum->date,
'transaction_number' => $module . $datum->number,
'module_id' => $module_id,
'vat_id' => $datum->vat->id,
'vat_code' => $datum->vat->code.' - '.$datum->vat->name,
'vat_rate' => $datum->vat_rate,
'net_of_vat' => $datum->net_of_vat,
'amount_due' => $datum->amount_due,
'balance' => $datum->vat_balance,
'amount_to_apply' => $datum->vat_balance,
];
}
return $items;
}
We merged the purchase & direct payments, same goes with sale & direct collection
$purchases = Purchase::select(
'id',
'number',
'date_delivered',
'vat_id',
'vat_rate',
'net_of_vat',
'amount_due',
'vat_balance'
)
->where('level_id',4)
->where('vat_balance','>', 0)
->where('company_id',Auth::user()->company_id)
->search(trim($this->input_search))
->orderBy('id', $this->order)
->get();
$purchases_input_tax = $this->setToInputOutputTax($purchases,'P-',201);
$direct_payments = DirectPayment::select(
'id',
'number',
'date',
'vat_id',
'vat_rate',
'net_of_vat',
'amount_due',
'vat_balance'
)
// ->union($purchases)
->where('level_id',4)
->where('vat_balance','>', 0)
->where('company_id',Auth::user()->company_id)
->search(trim($this->input_search))
->orderBy('id', $this->order)
->get();
// ->paginate(10, ['*'], 'input');
$direct_payments_input_tax = $this->setToInputOutputTax($direct_payments,'DP-',210);
$input_tax = array_merge($purchases_input_tax,$direct_payments_input_tax);
$col = collect($input_tax);
$input_currentPage = Paginator::resolveCurrentPage();
$currentPageItems = $col->slice(($input_currentPage - 1) * $this->input_size, $this->input_size)->all();
$all_input_taxes = new Paginator($currentPageItems, count($col), $this->input_size);
$sales = Sale::where('level_id',4)
->where('vat_balance','>', 0)
// ->where('status_id',[3,9])
->where('company_id',Auth::user()->company_id)
->search(trim($this->output_search))
->orderBy('id', $this->order)
->get();
// ->paginate(10, ['*'], 'output');
$sales_output_tax = $this->setToInputOutputTax($sales,'S-',101);
$direct_collections = DirectCollection::where('level_id',4)
->where('vat_balance','>', 0)
->where('company_id',Auth::user()->company_id)
->search(trim($this->output_search))
->orderBy('id', $this->order)
->get();
// ->paginate(10, ['*'], 'output');
$direct_collections_output_tax = $this->setToInputOutputTax($sales,'DC-',110);
$output_tax = array_merge($sales_output_tax,$direct_collections_output_tax);
$output_col = collect($output_tax);
$output_currentPage = Paginator::resolveCurrentPage();
$output_currentPageItems = $output_col->slice(($output_currentPage - 1) * $this->output_size, $this->output_size)->all();
$all_output_taxes = new Paginator($output_currentPageItems, count($output_col), $this->output_size);
Question: Is it possible to convert the array to same format of the model? Reason why we need to do this is because we need to paginate the new format
I'm modifying a Wordpress API witch is currently getting learnpress course and lessons infos from the database using leanrpress functions only. I need to modify the API to get the scores from the newly implemented plugin h5p, therefor i need to make a new function to access the Database and get the scores from the right table, then put then into an array with the according lesson. The array here is only an exemple i'm using to see if i can get the datas, ut i'm stuck with the error
"Call to a member function execute() on string"
when i try and run it on postman. Could someone lighten me on this issue please ?
function ilp_api_get_progress_by_mail($data){
$mail=$_GET['mail']; //$data->get_param["mail"];
$course_id=$_GET['course'];
global $wpdb;
$user=get_user_by("email",$mail);
if($user !== false){
$lp_user=learn_press_get_user( $user->ID );
if($course_id==NULL){
$all_courses=ilp_api_get_all_courses($data);
}else{
$all_courses=array('courses' => array(array('id' => intval($course_id))));
}
$progress=array();
$i=0;
if($all_courses!=NULL && $all_courses['courses']!=null){
foreach($all_courses['courses'] as $course){
if($lp_user->has_enrolled_course($course['id'])){
$lp_course=learn_press_get_course( $course['id'] );
$course_data = $lp_user->get_course_data($course['id']);
$course_results = $course_data->get_results( false );
$progress[$i]=array(
'id' => $course['id'],
'name' => $lp_course->get_title(), //$course['name'],
'condition' => $lp_course->get_passing_condition(),
'completed' => $course_results['completed_items'],
'total' => $course_results['count_items'],
'progress' => absint( $course_results['completed_items'] / $course_results['count_items'] * 100 ),
'permalink' => $lp_course->get_permalink(),
);
$i++;
}
}
}
$result = array(
'userfound' => true,
'user_id' => $user->ID,
'connect' => get_h5p_grades(),
'courses_progress' => $progress,
'course_id' => $all_courses,
);
function get_h5p_grades(){
global $wpdb;
$ID = 1;
$ID_use = 1;
$result = $wpdb->prepare('SELECT score FROM mci_h5p_results WHERE id = %d AND user_id = %d', $ID, $ID_use);
$result->execute();
$donnees = $result->fetch();
return $donnees;
}
I'm running Laravel 5 and have built a small search function:
$q = Input::get('q');
$search_terms = explode(' ', $q);
$user_query = User::select();
$news_query = Article::select();
foreach ($search_terms as $term) {
$user_query->where('username', 'like', '%' . $term . '%');
$news_query->where('title', 'like', '%' . $term . '%');
}
$user_results = $user_query->get();
$news_results = $news_query->get();
return view('search', ['q' => $q, 'user_results' => $user_results, 'news_results' => $news_results]);
It works for one search term, but doesn't quite work with multiple words.
Example:
"boss" returns users and news items that contain "boss"
"boss man" returns users and news items that contain "boss"
"man boss" returns users and news items that contain "man"
How can I make adjustments so it will return users and news items that contain "boss" or "man" ?
Right now, your query is executed using and statements, so MySQL is looking for usernames consisting of both boss and man.
You can change to orWhere() and it should work right away. Here's a quick experiment I did in Tinker using your code:
$terms = explode(' ', 'c a');
$user_query = User::select();
foreach ($terms as $term) {
$user_query->orWhere('username', 'like', '%' . $term . '%');
}
$user_results = $user_query->get();
$user_results->toArray();
// array(
// 0 => array(
// 'id' => 2,
// 'username' => 'christopher',
// 'created_at' => '2014-04-27 18:41:56',
// 'updated_at' => '2014-11-07 13:42:58',
// 'remember_token' => NULL
// ),
// 1 => array(
// 'id' => 4,
// 'username' => 'Kalle',
// 'created_at' => '2014-11-07 13:42:55',
// 'updated_at' => '2014-11-07 13:42:55',
// 'remember_token' => NULL
// )
// )
I'm trying to pass variable to the view and this one is very weird as the naming and directory structure is correct. Below is the function in my controller:
public function validate_apply_link(){
App::uses('CakeEmail', 'Network/Email');
$this->layout = 'blank';
$listings = $this->CareersAndJob->query("
SELECT l.sid, l.title, lp.value, u.CompanyName, u.WebSite
FROM listings l
LEFT JOIN listings_properties lp
ON lp.object_sid = l.sid
LEFT JOIN users u
ON u.sid = l.user_sid
WHERE l.active = 1
AND lp.add_parameter = 2
AND l.JobGateSenderReference IS NULL
AND u.CompanyName != 'AECOM'
ORDER BY u.CompanyName ASC
LIMIT 5
");
$doc = new DOMDocument();
ob_start();
$listing_count = count($listings);
echo nl2br("Checking $listing_count active jobs...\n\n");
$i=0;
foreach($listings as $listing){
$sid = $listing['l']['sid'];
$url = $listing['lp']['value'];
$company_name = $listing['u']['CompanyName'];
$title = htmlspecialchars($listing['l']['title']);
$length = strpos($title, "-");
if($length != 0){
$title = substr($title, 0, $length-1);
}
$title = substr($title, 0, $length-1);
$title = substr($title, 0, 10);
$data = $this->curl($url);
$check_pdf = strpos($data['info']['content_type'], "pdf");
if($check_pdf != false){
$outputs['data'][$i]['url'] = $url;
$outputs['data'][$i]['sid'] = $sid;
$outputs['data'][$i]['title'] = $title;
$outputs['data'][$i]['company_name'] = $company_name;
$outputs['data'][$i]['our_link'] = "http://careersandjobs.com.au/display-job/{$sid}";
$outputs['data'][$i]['content_type'] = $data['info']['content_type'];
$outputs['data'][$i]['data_type'] = 'pdf';
$i++;
continue;
}
#$doc->loadHTML($data['results']);
$html = $doc->saveHTML();
$xpath = new DOMXpath($doc);
$body = $doc->getElementsByTagName('body')->item(0);
$parsed_url = parse_url($url);
switch($parsed_url['host']){
case "www.michaelpage.com.au":
parse_str($url);
$exist = $xpath->query("//*[contains(#value,'{$ref}')]");
break;
case "https://vacancies.mackay.qld.gov.au":
parse_str($url);
$exist = $xpath->query("//*[contains(#value,'{$title}')]");
break;
default:
$exist = $xpath->query("//*[contains(text(),'{$title}')]");
break;
}
if($exist->length == 0){
if(strpos($url, '#') == false){
$outputs['data'][$i]['url'] = $url;
$outputs['data'][$i]['sid'] = $sid;
$outputs['data'][$i]['title'] = $title;
$outputs['data'][$i]['company_name'] = $company_name;
$outputs['data'][$i]['our_link'] = "http://careersandjobs.com.au/display-job/{$sid}";
$outputs['data'][$i]['content_type'] = $data['info']['content_type'];
$response_code = $this->http_response_codes($data['info']['http_code']);
$outputs['data'][$i]['response_code'] = $response_code;
$outputs['data'][$i]['data_type'] = 'title_not_found';
}else{
$outputs['data'][$i]['data_type'] = 'no_iframe';
}
$i++;
}
flush();
ob_flush();
}
$this->set(compact('outputs'));
}
I can do pr on the outputs variable in the view but this outputs to NULL but when I delete the entire bunch of code inside the controller function and just pass a test variable through it works.
Is there something wrong with the function that I am not aware of?
No errors were found in the above function by the way
app/Controller/CareersAndJobsController.php (line 1048)
array(
'data' => array(
(int) 0 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225055',
'sid' => '3649',
'title' => 'Graduate P',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3649',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
),
(int) 1 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225724',
'sid' => '3726',
'title' => 'Program &a',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3726',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
),
(int) 2 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225826',
'sid' => '3727',
'title' => 'Road Netwo',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3727',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
)
)
)
This is what I am getting from outputs variable just before it gets set by the set function in controller
Any reason you chose to use CakePHP? Because you seem to not make use of its functionality!
You're using literal SQL queries, therefore basically skipping the Models functionality.
You're outputting your content from your Controller? Be careful when using output buffering, this may conflict with CakePHP's inner workings, which also relies on output buffering in many cases. Because you're already outputting the content here (ob_flush()), you'll be outputting your content before your View is reached..
Normally I would point to specific points in the manual, however, because there's so much wrong here, I would suggest to start reading at the beginning
Basically I have 2 methods in the same class, getMovie and getGenres. They are very similar but One doesn't return what I expect.
Here's getMovie method:
public function getMovie($argType, $arg){
$movieQuery = "SELECT id,
rt_id,
imdb_id,
url,
rt_url,
type,
adult,
DATE_FORMAT(release_date, '%Y') AS year,
date_added,
title,
runtime,
budget,
revenue,
homepage,
rating,
tagline,
overview,
popularity,
image,
backdrop,
trailer
FROM movies
WHERE " . $argType . " = " . $arg;
$movieResult = $this->_query($movieQuery);
$movies = array();
if($movieResult->fetch_array(MYSQLI_ASSOC)){
while($m = $movieResult->fetch_array(MYSQLI_ASSOC)){
$movies[] = array( 'title' => $m['title'],
'duplicate' => $m['duplicate'],
'url' => $m['url'],
'rt_url' => $m['rt_url'],
'release_date' => $m['release_date'],
'date_added' => $m['date_added'],
'type' => 'movie',
'adult' => $m['adult'],
'id' => $id,
'rt_id' => $m['rt_id'],
'imdb_id' => $m['imdb_id'],
'rating' => $m['rating'],
'tagline' => $m['tagline'],
'overview' => $m['overview'],
'popularity' => $m['popularity'],
'runtime' => $m['runtime'],
'budget' => $m['budget'],
'revenue' => $m['revenue'],
'homepage' => $m['homepage'],
'image' => $m['image'],
'backdrop' => $m['backdrop'],
'trailer' => $m['trailer'] );
}
return $movies;
}
else{
return false;
}
Here's getGenres method:
public function getGenres($movieId = NULL){
$genresQuery = "";
if($movieId != NULL){
$genresQuery = "SELECT id,
name
FROM genres
WHERE id = ANY (
SELECT genre_id
FROM movie_genres
WHERE movie_id = " . $movieId . ")";
}
else{
$genresQuery = "SELECT id,
name
FROM genres";
}
$genresResult = $this->_query($genresQuery);
$genres = array();
if($genresResult->fetch_array(MYSQLI_ASSOC)){
while($genre = $genresResult->fetch_array(MYSQLI_ASSOC)){
$genres[] = array( 'id' => $genre['id'],
'name' => $genre['name'] );
}
return $genres;
}
else{
return false;
}
}
And here's how I call them:
$mov = $movie->getMovie(2207);
print_r($mov); // output: Array()
$gen = $movie->getGenres(2207);
print_r($gen); // output: Array(values inside)
Both queries do actually return expected values but getMovies method doesn't work with the if statement. It works fine if I just have while loop.
I am using if as well as while as I heard that while loop can sometimes execute even when there's not values. Is there any truth to this? If there is indeed a reason to use an if statement as well as wile loop then why doesn't it work with getMovies method?
Edit 1: I tried storing the array like so but that resulted in a memory related error:
$r = $genresResult->fetch_array(MYSQLI_ASSOC);
if($r){
while($r){
$genres[] = array( 'id' => $genre['id'],
'name' => $genre['name'] );
}
return $genres;
}
I am using if as well as while as I heard that while loop can sometimes execute even when there's not values. Is there any truth to this?
No, according to the php manual mysqli_result::fetch_array returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in resultset.
Null is falsy so the while loop will not be entered.
Although the if statement is unnecessary if you had one you would use mysqli_result::$num_rows to check if the query returned any rows.
if($movieResult->num_rows > 0){
while($m = $movieResult->fetch_array(MYSQLI_ASSOC)){
...
}
}