Trying to get ID by findBySlug method in CakePHP, for example
$this->Page->findBySlug(1);
this will return all fields, but i need only ID to be returned , i have searched lot but could not find function reference as well and try following but get an Error
$this->Page->findBySlug(15, array('fields'=>array('Page.id')));
any solution within the function that doesn't use a custom query?
cakephp2
$page = $this->Page->findBySlug(1, array('id'));
$id = $page['Page']['id'];
cakephp3
$page = $this->Pages->findBySlug(1)
->select('id');
$id = $page->id;
Related
Here's my Database Structure:
Products : ['id','name','image']
Request : ['id','marketer_id','distributor_id']
RequestItems : ['id','request_id','product_id','quantity']
Now this is just a short example of structure. what I'm trying to do is that, I have a page with request, which in this page I'm getting items in a request base on RequestItems table, and i want to add a button in my page to add product to this request, but i want to show products that are not exist in RequestItems.
I can make a condition to check before adding product to make sure user won't add 1 product 2 times in a request, but i also want to make it clear that user see products in add button which it's already exist in his request items.
I just need help for Query, I'm developing with Laravel & vue.js for SPA.
My Solution (But looking for better Solution) :
public function getRequestRepresentativeSideProducts(RepresentativesRequests $id, Request $request){
$products = DistributorProducts::where(
'distributor_id', $request->distributor_id
)
->latest()
->get();
$data = $id->items()->latest()->get();
$myArray = array();
for ($i = 0; $i < $data->count(); $i++)
{
$myArray[] = $data[$i]->product_id;
}
return $products->except($myArray);
}
Edit 01 : I've managed to get response with below query, but It's taking all data
$data = DistributorProducts::doesntHave('requestRepresentativeSideItems', 'and', function ($query){
$query->where('representative_request_id', '=', 1);
})->where('distributor_id', $request->distributor_id)
->latest()
->get();
$data = DistributorProducts::whereDoesntHave('requestRepresentativeSideItems', function (Builder $query) use ($id) {
$query->where('representative_request_id', 'like', $id->id);
})->where('distributor_id', $request->distributor_id)
->latest()
->get();
$data = DistributorProducts::whereDoesntHave('requestRepresentativeSideItems', function (Builder $query) use ($id) {
$query->where('representative_request_id', $id->id);
})->where('distributor_id', $request->distributor_id)
->latest()
->get();
I have 3 products for distributor_id which 2 of them are in request items, so my query should show 1 but will above query still I'm getting all products.
Edit 02: I've checked where from $query and used like too and changed request_id but didn't changed result at all. looks like it's just ignoring that part.
Presuming you have the id for the Request you wanted to filter out, the SQL query will be roughly looked like
SELECT * FROM `products` WHERE NOT EXISTS
(SELECT * FROM `request_items` where `products`.`id` = `product_id` and `request_id` = ? )
I had to make additional assumtion as you didnt provide the model, i'd just assume the following
class Product extends Model
{
public function requestItems()
{
return $this->hasMany(RequestItems::class);
}
}
class RequestItems extends Model
{
public function products()
{
return $this->belongsTo(Product::class);
}
}
Then we can use doesntHave query criteria to find products that dont have relationship with
the RequestItems for given request id (in this example its 1).
Products::doesntHave('requestItems', 'and',
function($query){ $query->where('request_id', '=', 1); }
);
Hope it helps. I havent tried it myself, but i believe it would works. You can use toSql
method to see its resulting SQL query.
Note: some insight on the differece of IN and EXISTS
I want to get the value from the array I've passed from the first view to another view.
I found this works by using route (not url), but I don't know how to get it without parameter in the controller.
Please help me within the right syntax.
This is the latest code I've tried
$id = $request->id;
if($request->has('download', 'id')){
$pdf = PDF::loadView('pdfview');
return $pdf->download('pdfview.pdf',['id'=>$id])->with('id',$id);}
This is my code *used to download pdf file from a view
Controller
public function pdfview(Request $request)
{
$items = DB::table("items")->get();
view()->share('items',$items);
$id = $request->only(['id']);
if($request->has('download', 'id')){
$pdf = PDF::loadView('pdfview');
return $pdf->download('pdfview.pdf', ['id'=>$id])->with('id', $id);
}
return view('pdfview', ['id'=>$id])->with('id', $id);
}
Route
Route::get('pdfview',array('as'=>'pdfview','uses'=>'MaatwebsiteDemoController#pdfview'));
View
Download PDF
I want to get the $employee->nip value
But it is still Undefined variable: id
Don't really have time to test it. But this thread looks promising.
https://laravel.io/forum/03-14-2016-basics-passing-info-from-one-view-to-another
I want to know how can i get all data of user with array id for where condition
In yii you could do something like this
$students = Student::model()->findAll("id IN ({$_POST['studentIds']})");
or
$userDtls = Student::model ()->findAllByAttributes ( array (
'id' => explode ( ",", $_POST ['studentIds'] )
) );
Now in yii2 CDbCriteria is not there, so which approach should i use to achieve same thing??
I have tried this but it only returns data for first id in the array
$result = Users::findAll([ 'id'=> $_POST ['keylist']]);
In documentation it is written that we can use this
$result = Users::findAll([1,488,489]);
But my array $_POST['keylist'] is something like this
keylist{
0='1'
1='5'
2='8'
}
I have also tried this
$ids = \Yii::$app->request->post('keylist', []);
$result = Users::findAll($ids);
And still returns data for first id in the array here is the screenshot
Thats why it doesnt work i guess
thank you
$users = Users::findAll($ids); is a correct approach.
See what you can pass in $ids in official docs here.
As I explained you here, you should never trust data from $_POST and check it for existence and validate before using.
Example of getting and check for existence with Yii2:
$ids = \Yii::$app->request->post('ids');
Or just:
$ids = isset($_POST['ids']) ? $_POST['ids'] : null;
For more complex cases I'd recommend to create separate search model and use it with validation, see Gii's CRUD for example.
UPDATE: Pay attention to what you actually pass as $ids.
$students_ids = Yii::$app->request->post('studentIds');
if(isset($students_ids)) {
$result = Users::find()->where(['in','id',$students_ids])->all();
}
var_dump($result)
Try like this
I want to list the posts of a given user. It work but paginate is not accurate.
My code is the following
public function index($userid = null) {
if ($this->Post->exists($userid)) {
$this->set('posts',$this->Post->find('all',array('conditions'=>array('user_id'=>$userid))),
$this->paginate());
} else
{
$this->Post->recursive = 0;
$this->set('posts', $this->paginate());
}
The result give the correct list --> 3 posts, but the paginator display page number 1 and 2
Can you help me?
Thank you
Refer to the documentation
The code in the question is quite confused.
find
The find method only has two parameters:
find(string $type = 'first', array $params = array())
The third parameter (the result of calling paginate) isn't used and will be ignored - but it will setup the view variables for the pagination helper, based on the conditions used in the paginate call - there are no conditions being used.
It is not possible to paginate the result of a find call - to do so restructure the code to call paginate instead of find.
paginate
The paginate method is just a proxy for the paginator component - it can be used in several ways, this one (controller code example):
$this->paginate($conditions)
Is the most appropriate usage for the case in the question i.e. the complete action code should be similar to:
public function index($userId = null) {
$conditions = array();
if ($userId) {
$conditions['Post.user_id'] = $userId;
}
$this->set('posts',$this->paginate($conditions));
}
Note that logically, if a user id is requested that doesn't exist the response should be nothing - not everything.
I'm quite sure that conditions for paginate do now work that way.
If you want to set conditions for paginations you should do it as follows:
$this->paginate = array('conditions' => array('Post.user_id' => $userid)));
$this->set('posts', $this->paginate());
And yes, the result stored in $posts ( in view ) will be proper as you assigned proper find result to it, meanwhile you've paginated post model without any conditions whatsoever.
First off, you're checking to see if the post exists but using the $userid. Are you trying to see "if the user exists, get the posts for that user, or else get posts for ALL users"? As you have it right now, say you have the $userid = 159, but the max Post.id in your database is 28, then the condition is not being met because it is checking to see whether or not there is a Post with the id = 159 that exists, which it doesn't.
Second, your conditions are wrong. You are performing a find and then a paginate which are two separate queries. The conditions are being implemented on the find query but not the paginate but you are only displaying the find results.
public function index($userid = null) {
// setting recursive outside of if statement makes it applicable either way
$this->Post->recursive = 0;
// check if user exists
if ($this->Post->User->exists($userid)) {
// get posts for user
$this->set('posts', $this->paginate('Post', array('Post.user_id' => $userid));
}
else{
// get all posts
$this->set('posts', $this->paginate('Post'));
}
} // end index function
I searched a lot but I couldn't find on How to use the find('all') in Views as used in Rails, but here I'm getting the error "Undefined property: View::$Menu [APP\Lib\Cake\View\View.php, line 804]"
'Menu' is the model which I'm using to fetch data from the menus table.
I'm using the below code in views:
$this->set('test',$this->Menu->find('all'));
print_r($test);
Inside your Menu model create a method, something like getMenu(). In this method do your find() and get the results you want. Modify the results as you need and like to within the getMenu() method and return the data.
If you need that menu on every page in AppController::beforeFilter() or beforeRender() simply do
$this->set('menu', ClassRegistry::init('Menu')->getMenu());
If you do not need it everywhere you might go better with using requestAction getting the data using this method from the Menus controller that will call getMenu() from the model and return the data. Setting it where you need it would be still better, if you use requestAction you also want to cache it very likely.
TRY TO NOT RETRIEVE DATA WITHIN VIEW FILE. VIOLATION OF MVC RULE
try this in view file:
$menu = ClassRegistry::init('Menu');
pr($menu->find('all'));
In AppHelper ,
Make a below function
function getMenu()
{
App::import('Model', 'Menu');
$this->Menu= &new Menu();
$test = array();
$test = $this->Menu->find('all');
return $test;
}
Use above function in view like :
<?php
$menu = $html->getMenu();
print_r($menu);
?>
Cakephp not allow this .
First create the reference(object) of your model using ClassRegistry::init('Model');
And then call find function from using object
$obj = ClassRegistry::init('Menu');
$test = $obj->find('all');
echo ""; print_r($test); `
This will work.