I am making a laravel application, Here i can 'filter' out my 'files' first by role (assigned to the user), Folder and then subfolders. for the query i use a for loop, but this can return different values depending on the 'filters' i use.
Now laravel returns this error message:
SQLSTATE[HY093]: Invalid parameter number
Query:
select * from `file` where `id` in (8, 12, 13, ?, ?, ?)
Now i want to ignore those '?' and keep it from returning an error, i know this is doable by making the '?' NULL. but i cant find a way to do that
the code:
public function show($id)
{
$user = Auth::user();
$userid = $user->id;
$role_id = $user->role_id;
$folders = Folder::all();
$file_role = File_Role::where('role_id', '=', $role_id)->pluck('file_id');
// dd($file_role[1]);
$count = count($file_role);
$i = 0;
var_dump($file_role);
for($i = 0; $i < $count; $i++) {
$file[] = File_Subfolder::where('subfolder_id', '=', $id)->where('file_id', '=', $file_role[$i])->pluck('file_id');
}
$chosenfile = File::whereIn('id', $file)->get();
return view('partner.subquents.sub_file', compact('chosenfile'));
}
$file returns 8,12,13,?,?,? in this case. this can change depending on the filters
i tried an foreach loop.and i tried to find on the internet how to assign NULL to '?' values
as you can see in my DD that some dont give data back, but some do
Can u try this:
$fileSubFolderCount = File_Subfolder::where('subfolder_id', '=', $id)->where('file_id', '=', $file_role[$i])->pluck('file_id')->count();
$file[] = $fileSubFolderCount > 0 ? File_Subfolder::where('subfolder_id', '=', $id)->where('file_id', '=', $file_role[$i])->pluck('file_id') : null;
Related
I'm trying to get all item series from a deposit but the deposit id is on a related table. On this function i'll list all the series between two sequences requested
public function getSeries($params = [])
{
$data = collect($params);
$inicio = $data->only('serie_in');
$fim = $data->only('serie_fi');
$depOrigem = $data->only('id_origem');
$series = [];
for($i = $inicio; $i <= $fim; ++$i)
{
$item = Item::leftJoin('produtoItem', 'produtoItem.id', '=', 'item.id_produtoItem')->where('serie', $i)->where('produtoItem.id_deposito', $depOrigem)->first();
if(empty($item))
{
$status = 'I';
}
else
{
$status = $item->status;
}
$series[] = [
'serie' => $i,
'status' => $status
];
}
$result = [
'status' => true,
'data' => $series
];
return $result;
}
This is the error message, i'm thinking that must be as sintax error, but a dont realy know what? Can you help me?
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 2031 (SQL: select * from item left join produtoItem on produtoItem.id = item.id_produtoItem where serie = ? limit 1) in file /usr/share/nginx/html/controleestoque/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 671
I was calling the request on my controller without a validator, so i rewrite the getSeries method.
public function getSeries(Request $request){
$data = $request->only(['serie_in', 'serie_fi', 'id_origem']);
$result = $this->produto_service->getSeries($data);
return response()->json($result);
}
And my function work it !
I am new to PHP and new to Laravel. I'm taking over an old project.
We had this code and it was working fine:
public function getList(Request $request)
{
$apiFormat = array();
try
{
$perPage = Input::get('page_size', 10);
$filters = $request->input();
$postRepo = new PostRepo();
$user = $_SESSION["user"];
$listPost = $postRepo->getlist($user->id, $perPage, 0);
$apiFormat['status'] =\Config::get('constants.api.STATUS_OK');
$apiFormat['message'] = \Config::get('constants.api.SUCCESS');
$apiFormat['data'] = $listPost;
} catch (\Exception $ex) {
$apiFormat['status'] =
\Config::get('constants.api.STATUS_ERROR');
$apiFormat['message'] = $ex->getMessage();
}
return response()->json($apiFormat);
}
This returned 10 items that would show up on our newsfeed.
This line:
$listPost = $postRepo->getlist($user->id, $perPage, 0);
Did a database call like this:
$sqlCheckHasLike = "SELECT count(*) > 0 FROM `likes` WHERE `post_id` = `posts`.`id` and `user_id` = '".$user_id."'";
$query = DB::table('posts')
->select('posts.*',DB::raw("($sqlCheckHasLike) as is_like"), 'users.full_name', 'users.avatar', DB::raw("post_categories.name as post_categories_name"))
->leftJoin('users', 'posts.user_id', '=', 'users.id')
->leftJoin('post_categories', 'post_categories.id', '=', 'posts.post_category_id')
->where('posts.status',$post_status)
->where('users.status', 1)
->where(function ($query) use ($user_id, $list_user) {
$query->whereIn('user_id', $list_user)
->orwhere('user_id', $user_id);
})
->orderBy('created_at', 'desc')->paginate($pageSize);
return $query;
However, we've just added comments to each item in the newsfeed. That code is handled elsewhere, but here I want to find, given a post.id, how many comments belong to it? This needs to be included in the response.
Replacing the first method, I tried this:
try {
$perPage = Input::get('page_size', 10);
$filters = $request->input();
$postRepo = new PostRepo();
$user = $_SESSION["user"];
$listPost = $postRepo->getlist($user->id, $perPage, 0);
$array_of_rows = [];
foreach ($listPost as $lp) {
$row_as_array = (array) $lp;
$post_id = $lp->id;
$query = "select count(id) as how_many from comments where
post_id = '". $post_id ."'";
$result_array = DB::select($query);
$result_obj = $result_array[0];
$how_many = $result_obj->how_many;
$row_as_array['how_many_comments'] = $how_many;
$array_of_rows[] = $row_as_array;
}
$merged_list_post = (object) $array_of_rows;
file_put_contents("/var/log/api_debugging", "\ncomment count:\n",
FILE_APPEND | LOCK_EX);
file_put_contents("/var/log/api_debugging",
print_r($merged_list_post, true), FILE_APPEND | LOCK_EX);
$apiFormat['status'] = \Config::get('constants.api.STATUS_OK');
$apiFormat['message'] = \Config::get('constants.api.SUCCESS');
$apiFormat['data'] = $merged_list_post;
} catch (\Exception $ex) {
$apiFormat['status']=\Config::get('constants.api.STATUS_ERROR');
$apiFormat['message'] = $ex->getMessage();
}
This does not throw an error (there are no Exceptions) but it changed the returned data, such that the apps which consume this feed no longer get what they need.
Is there an official approach in Laravel that makes it easy to do several database queries, and combine that data at a per inner object level? I'd like to avoid returning an object that is of a different type than the one in the original example.
You could just modify the original query (I've just included the first few lines here) to JOIN the comments table and get the count:
$query = DB::table('posts')
->select('posts.*',DB::raw("($sqlCheckHasLike) as is_like"), 'users.full_name', 'users.avatar', DB::raw("post_categories.name as post_categories_name"), DB::raw("count(comments.id) as how_many"))
->leftJoin('users', 'posts.user_id', '=', 'users.id')
->leftJoin('post_categories', 'post_categories.id', '=', 'posts.post_category_id')
->leftJoin('comments', 'comments.post_id', '=', 'posts.id')
You will also need to add a groupBy clause:
->groupBy('posts.id')
prior to the orderBy.
I have a query in PHP(MySQL). I am fetching records from a table and returning them to a datatable.
The problem is it always returns 1 when I use count() with the query.
However, if I count the elements of the array, then the result is as expected. It returns all 8 records.
Following is my code:
public function job_order_detail_del($arr=array()) {
$count = 0;
$start = isset($arr['start'])?$arr['start']:0;
$length = isset($arr['length'])?$arr['length']:0;
$search = isset($arr['search'])?$arr['search']:'';
$orderBy = isset($arr['orderBy'])?$arr['orderBy']:'';
$orderDir = isset($arr['orderDir'])?$arr['orderDir']:'';
$aufnr = isset($arr['aufnr'])?$arr['aufnr']:0;
$aufpl = isset($arr['aufpl'])?$arr['aufpl']:0;
$type = isset($arr['type'])?$arr['type']:'';
$whr = array('h.stats' => '', 'h.bukrs' => Session::get('company'), 'h.delstats' => '');
if ($aufnr > 0)
$whr['a.aufnr'] = $aufnr;
if ($aufpl > 0)
$whr['a.aufpl'] = $aufpl;
$a = DB::table('zpp_afpo_h as h')
->leftjoin('zpp_afpo as a ', function($join) {
$join->on('a.aufnr', '=', 'h.aufnr')
->where('a.bukrs', '=', Session::get('company'))
->where('a.stats', '=', '');
})
->leftjoin('zpp_afvc as b ', function($join) {
$join->on('a.aufnr', '=', 'b.aufnr')
->on('a.aufpl', '=', 'b.aufpl')
->where('b.bukrs', '=', Session::get('company'))
->where('b.stats', '=', '');
})
->leftjoin('zpp_afru as c ', function($join) use($type) {
$join->on('c.aufnr', '=', 'b.aufnr')
->on('c.rueck', '=', 'b.rueck');
})
->where('c.type', '=', $type)
->where('c.bukrs', '=', Session::get('company'))
->where('c.stats', '=', '')
->where('c.delstats', '=', '')
->select('h.idat2', 'a.matnr', 'b.arbpl', 'a.gamng as total', 'b.rueck', 'h.priority', 'b.vornr', 'b.prev_startper', 'b.scrap', 'h.dispatch_date', 'h.order_start_dt', 'h.requirement_dt', 'h.ktxt', 'c.rmzhl', 'c.budat', 'c.aufnr', 'c.rework_lmnga', DB::raw('sum(c.lmnga) as sum_cnfrm'));
if ($aufnr == '') {
$a->where('h.idat2', '=', '0000:00:00');
}
$a->where($whr)
->groupby('b.rueck')
->groupby('c.rmzhl')
->groupby('c.counter');
if($orderBy!=''){
$a->orderBy($orderBy,$orderDir);
}
if($search!=''){
$dt_srch = implode('-',array_reverse(explode('-',$search)));
$a->where(function($query) use ($search,$dt_srch){
$query->where('c.aufnr','LIKE','%'.$search.'%')
->orWhere('a.matnr','LIKE','%'.$search.'%')
->orWhere('c.budat','LIKE','%'.$dt_srch.'%')
->orWhere('b.arbpl','LIKE','%'.$search.'%')
->orWhere('a.gamng','LIKE','%'.$search.'%');
});
}
if($length>0){
$get_rec = $a->skip($start)->take($length)->get();
}else{
$get_rec = $a->get();
$count = count($get_rec);
// $count = $a->count(); //Problem is here
return $count;
}
$arr = array();
foreach($get_rec as $l){
if($length>0 || Input::get('open') == 1 || Input::get('open') == 2){
$arr = DB::table('maras')
->where('matnr','=',$l->matnr)
->where('bukrs','=',Session::get('company'))
->where('stats','=','')
->where('delstats','=','')
->select(DB::raw('GROUP_CONCAT(distinct(matnr)) as mat'),DB::raw('GROUP_CONCAT(distinct(mdesc)) as mat_desc'))
->groupby('matnr')
->first();
$l->matnr = $arr->mat;
$l->mat_desc = $arr->mat_desc;
}
}
return $get_rec;
}
Please let me know the problem. Thanks in advance.
You are using count on groupBy element and count is returning only the grouped count. That's why it is returning only single row or 1. You could count the returned collections in this case like-
$count = $get_rec->count();
I am new to Laravel and was developing small application for my practise. I am doing job search functionality. This error giving me alot trouble and confuses me alot.
public function job_search(Request $request) {
$search_skill_set = $request->job_skills;
$search_results = JobPost::whereRaw('FIND_IN_SET(?, job_skills)', $search_skill_set)
->get()
->toArray();
for ($i = 0; $i < count($search_results); $i++) {
$department_id = (int)$search_results[$i]['department_name'];
$department_name = Department::select('department_name')
->where('id', '=', $department_id)
->get()
->toArray();
// the next statement raises an Undefined:offset 1 error
$search_results[$i]['department_name_info'] = $department_name[$i]['department_name'];
}
var_dump($search_results);
}
I am not getting where am i doing wrong, so any suggestion from given snippet and any modification in the code
change this line:
$search_results[$i]['department_name_info'] = $department_name[$i]['department_name'];
to
$search_results[$i]['department_name_info'] = $department_name[0]['department_name'];
for ($i=0; $i < count($search_results) ; $i++) {
$department_id = (int)$search_results[$i]['department_name'];
//I am getting department id correct here
$department_name = Department::select('department_name')->where('id','=',$department_id)->get()->toArray();
//$depratment_name is also going okay and working
$search_results[$i]['department_name_info'] = $department_name[0]['department_name'];
// This line should have a static index.
}
How can i get the id of $previous variable. When i try to get it as i mentioned below i am getting
Trying to get property of non-object
error on line 3. Any help would be appreciated.
$vehicle = Vehicle::find($id);
$previous = Vehicle::where('id', '<', $vehicle->id)->max('id');
if ($previous -> id == 3) {
$previous = Vehicle::find(3);
}
Most probably you don't have a Vehicle with the given id $id. So then your $previous is null. Hence, you get that error. It's a runtime error and you should examine your database, in particular your vehicles table.
Try this and look at the result:
$vehicle = Vehicle::find($id);
dd($vehicle);
$previous = Vehicle::where('id', '<', $vehicle->id)->max('id');
if ($previous -> id == 3) {
$previous = Vehicle::find(3);
}
I believe you won't get a Collection object back.
Always check if you got an object or null.
$vehicle = Vehicle::find($id);
if ($vehicle) {
$previous = Vehicle::where('id', '<', $vehicle->id)->max('id');
// other code
}
else {
// do something else
}
It's because you are using an aggregate function max. So the returned value is not an object but the max value as a string.
You could simply do,
if ($previous == 3) {
$previous = Vehicle::find(3);
}
or the following
$previous = Vehicle::where('id', '=', function($query) use ($vehicle)
{
$query->from(with(new Vehicle)->getTable())
->select(DB::raw('max(id)'))
->where('id', '<', $vehicle->id);
})->first();
Now you can perform $previous->id. No need for $previous = Vehicle::find(3), because it already is the vehicle object of that id