CakePHP 3.x OR In Find Condition With Multiple Same Fields - cakephp

I would like to query the database for
Plates.page_number => 1 OR Plates.page_number => Cover
I am attempting to use the following code, but I am not getting the results I am looking for because of a duplicate array key, how can I search the same field for two different values?
$query = $this->Ledgers->find('all', array(
'contain' => array(
'Plates' => [
'conditions' => [
'OR' => [
'Plates.plate_title' => 'Front Cover',
'Plates.page_number' => '1',
'Plates.page_number' => 'Cover' // Duplicate Array Key
]
]
], 'Plates.PlateImages', 'Tribes'
),
'conditions' => array(
'Ledgers.disabled' => 'n', 'Ledgers.id IN' => $ledgerIds
)
))->orderAsc('ledger_title');

Please try wrapping your conditions in separate arrays, eg:
'OR' => [
['Plates.page_number' => '1'],
['Plates.page_number' => 'cover'],
...
]
More info can be found in CakePHP docs:
Query Builder -> Advanced Conditions

Related

Error: SQLSTATE[42P01]: Undefined table: "Missing FROM-claouse entry for table

Hy I create a join query using cakephp find as shown below :
$test = $this->DiagnosisBind->find(
'all',
[
'table' => 'diagnosis_binds',
'alias' => 'dbinds',
'order' => 'dbinds.set_num ASC',
//'recursive' => 0,
'conditions' => [
'dbinds.deleted IS NULL',
'dbinds.diagnosis_id ='.$diagnosisData[0][0]['id']
],
'joins' => [
[
'type' => 'INNER',
'table' => 'diagnosis_treats',
'alias' => 'dtreats',
'conditions' => [
'dtreats.diagnosis_bind_id = dbinds.id'
]
],
[
'type' => 'INNER',
'table' => 'medical_masters',
'alias' => 'medmas',
'conditions' => [
'medmas.deleted IS NULL'
]
]
],
'fields' => [
'dtreats.id',
'dtreats.medical_name',
'dtreats.amount',
'dbinds.days'
]
]
);
When executing the query, I got this error :
I have read this post missing FROM-clause entry for table "Grupo" cakephp And solution is create a recursive (I have tried but failed) and use containable (I'm not suppose to create containable). So what's wrong in my find above. Thank you
Note:
I'm using cakephp 2.0
Postgresql
There are no table and alias options for query builder finders, they are only available for joins, so your main table will use the default alias as you can see in the query in the error message, and that alias is DiagnosisBind, hence using dbinds will cause an error.
Long story short, use DiagnosisBind instead of dbinds.
Side note, never ever inject data into single value conditions (or in the key of a key => value condition for that matter):
'dbinds.diagnosis_id ='.$diagnosisData[0][0]['id']
That's a possible SQL injection vulnerability!, always use the key => value syntax, or bindings:
'DiagnosisBind.diagnosis_id' => $diagnosisData[0][0]['id']

Cakephp - Finding records with no associated records

Ok, so I have this:
$user_id = AuthComponent::user('id');
$joins = [
['table' => 'subscriptions',
'alias' => 'Subscription',
'type' => 'INNER',
'conditions' => [
'Subscription.thread_id = Thread.id',
'Subscription.user_id = '.$user_id
]
]
];
$unsubscribed = $this->Thread->find('all',[
'contain' => [
'Subscription' => ['conditions' => ['Subscription.user_id' => $user_id]]
],
'joins' => $joins,
'fields' => ['name','modified'],
'limit' => 10
]);
debug($unsubscribed);
It basically finds all threads with a subscription attached to the current user.
What I really want though, is the negative result. Or in other words: all the threads that do not have a subscription by the current user?
Is there a way to make the conditions negative? Or something like that?
Assuming your relations are:
Thread hasMany Subscription
Subscription belongsTo Thread
Your SQL would be:
SELECT Thread.*
FROM threads AS Thread
LEFT JOIN subscriptions AS Subscription
ON Thread.id = Subscription.thread_id
AND Subscription.user_id = ##user_id##
WHERE Subscription.user_id IS NULL;
The key concept is that you need a LEFT JOIN, not an INNER JOIN. This SQL joins all threads to all of the user's subscriptions AND does not eliminate those thread rows which do not have a subscription (i.e., the purpose of the LEFT JOIN). Then only select records that don't have a subscription (as found in the WHERE clause)
Translating to Cakephp:
$user_id = AuthComponent::user('id');
$joins = [
['table' => 'subscriptions',
'alias' => 'Subscription',
'type' => 'LEFT',
'conditions' => [
'Subscription.thread_id = Thread.id',
'Subscription.user_id = '.$user_id
]
]
];
$unsubscribed = $this->Thread->find('all',[
'conditions' => ['Subscription.user_id' => null],
'joins' => $joins,
'fields' => ['name','modified'],
'limit' => 10
]);
debug($unsubscribed);

Can't get formhelper to pre-populate multiple records

I have a model called Category which hasMany Expense. I am trying to generate an accordion type interface where a user can expand a category and edit the expenses. I can generate the input fields but they don't seem to be in "edit" mode because they are not pre-populated.
I've searched online and found a few related articles such as this one CakePHP: How to update multiple records at the same time with the Form helper and also this one CakePHP: Form helper with saveMany() to edit multiple rows at once. I have tried to emulate their code but with no success.
My CategoriesController Index function looks like this ...
public function index($project_id) {
$data = $this->Category->find('all', array(
'conditions'=>array('Category.project_id' => $project_id),
'order'=>array('Category.category_name')
));
$this->set('categories', $data);
$this->request->data = $data;
}
I have read that cakephp2 requires $this->request->data to be set for FormHelper to work. But in the examples I have found online everyone seems to use the plural of the model name so I tried that as well.
My Categories\index.ctp looks like this. I'm not at the "accordion" stage yet. I'm just trying to get input boxes on the screen that are pre-populated.
$i=0;
foreach ($categories as $category)
{
echo $this->Form->input("Category.$i.category_id");
echo $this->Form->input("Category.$i.category_name");
$j=0;
foreach($category['Expense'] as $expense)
{
echo $this->Form->input('Expense.' . $j . '.expense_id');
echo $this->Form->input('Expense.' . $j . '.expense_name');
echo $this->Form->input('Expense.' . $j . '.dollar_amount');
echo $this->Form->input('Expense.' . $j . '.sqft_amount');
$j++;
}
$i++;
}
This code seems to be iterating properly because it spits out the correct input fields. The big problem right now is just getting the fields to pre-populate. It doesn't seem to be in "edit" mode and I'm worried that that will be a problem down the road when I try to save the data.
Also, I have tried it with and without $this->form->create('Category') at the top. It doesn't seem to make a difference.
The $categories array looks like this ...
array(
(int) 0 => array(
'Category' => array(
'category_id' => '1',
'category_name' => 'Category 1',
'category_index' => '1',
'project_id' => '1'
),
'Project' => array(
'project_id' => '1',
'project_name' => '131 Anndale Dr',
'project_sqft' => '1700',
'project_cost' => '318',
'project_cost_per_sqft' => '0'
),
'Expense' => array(
(int) 0 => array(
'expense_id' => '2',
'expense_name' => 'Nails',
'category_id' => '1',
'dollar_amount' => '50',
'sqft_amount' => '1',
'expense_index' => '2'
),
(int) 1 => array(
'expense_id' => '1',
'expense_name' => 'Wood',
'category_id' => '1',
'dollar_amount' => '99',
'sqft_amount' => '1',
'expense_index' => '1'
)
)
),
(int) 1 => array(
'Category' => array(
'category_id' => '3',
'category_name' => 'Category 2',
'category_index' => '2',
'project_id' => '1'
),
'Project' => array(
'project_id' => '1',
'project_name' => '131 Anndale Dr',
'project_sqft' => '1700',
'project_cost' => '318',
'project_cost_per_sqft' => '0'
),
'Expense' => array(
(int) 0 => array(
'expense_id' => '3',
'expense_name' => 'Bed',
'category_id' => '3',
'dollar_amount' => '99',
'sqft_amount' => '2',
'expense_index' => '1'
),
(int) 1 => array(
'expense_id' => '4',
'expense_name' => 'Chair',
'category_id' => '3',
'dollar_amount' => '70',
'sqft_amount' => '1',
'expense_index' => '2'
)
)
)
)
Any help would be greatly appreciated. Thanks!!
Coincidentally, I've been doing almost exactly the same thing today.
In order to automatically populate the form, you need to have your data in $this->data in the view. You can do this by assigning to $this->request->data in your controller.
Then you need to have your field names reflect the structure of that array exactly. So using your example, you might have:
echo $this->Form->input("$i.Category.category_name");
for the category fields, and
echo $this->Form->input("$i.Expense.$j.expense_id");
for your expense fields.

Cakephp pagination with join table field sort is not working

Cakephp pagination with join table sort is not working for join table fields. But for custom sql join query working fine. Please help me to come out.
See below sample code.. I have Artist.name join table field in order.
$this->paginate = array(
'fields' => array(
'id',
'Song.title',
'Song.date',
'Artist.id AS artist_id',
'Artist.name AS artist_name',
'COUNT(SongViews.id) AS views'
),
'group' => array('ArtistsSong.song_id'),
'recursive' => 0,
'limit' => 20,
'joins' => array(
array(
'table' => 'tbl_artists_songs',
'alias' => 'ArtistsSong',
'conditions'=> array('Song.id = ArtistsSong.song_id')
),array(
'table' => 'tbl_artists',
'alias' => 'Artist',
'conditions'=> array('Artist.id = ArtistsSong.artist_id')
),array(
'table' => 'tbl_song_views',
'alias' => 'SongViews',
'type' => 'left',
'conditions'=> array('SongViews.song_id = ArtistsSong.song_id')
),
),
'order' => array('Artist.name'=>'asc')
);
It is a bug in CakePHP.
However, there is a trick to do it.
You should add a virtual field in your primary model.
Assuming your primary model is Song, you should add this before calling paginate:
$this->Song->virtualFields = array(
'artist_name' => 'Artist.name'
);
And now, you can sort by artist_name.
This question was asked nearly 5 years ago, but I came across the same problem in CakePHP 3. I realised I needed to whitelist the field to allow for sorting:
$this->paginate = array(
...
'sortWhitelist' => array ('Artist.name')
);
The Paginator automatically whitelists fields from the original table but not from the JOINed tables.
$this->paginate = ['fields' => ['id', 'name', 'company_id'],
'contain' => [
'Companies' =>
[
'fields' => ['id', 'name'],
'sort'=>['name'=>'ASC']
]
'limit' => 10,
];
Sorting by columns in associated models requires setting sortWhitelist.
$this->paginate['order'] = [ 'Artist.name' => 'desc' ];
$this->paginate['sortWhitelist'] = ['Artist.name', 'Song.title'];
$this->paginate['limit'] = $this->paginate['maxLimit'] = 200;
In HTML you have to set below line in table header:
<?= $this->Paginator->sort('Song.title', __('Title')) ?>

How to access a related table field from a Controller?

I am trying to get an array structure of a database and a few of its fields from my controller.
The fields I want are: Document.id, Document.name, Document.submission_date, and the Requester.name which is joined with: Requester.id = Document.requester_id
In my Controller:
Method A:
$documents = $this->Document->find('list', array('fields' => array('Document.name', 'Requester.name', 'Document.submission_date')));
Can't seem to find 'Requester.name'
Method B:
$documents = $this->Document->find('list', array('fields' => array('Document.name', 'Requester.name', 'Document.submission_date'), 'recursive' => 0));
Gives me:
array(
'2012-08-17' => array(
'Document_A' => 'Requester_Z'
),
'2012-08-05' => array(
'Document_B' => 'Requester_Y'
),
'2012-07-09' => array(
'Document_C' => 'Requester_X'
)
)
But I need it to be in format:
array(
(int) 0 => array(
'id' => '16'
'submission_date' => '2012-08-17'
'name' => 'Document_A',
'requester_name' => 'Requester_Z'
),
(int) 1 => array(
'id' => '41'
'submission_date' => '2012-08-05'
'name' => 'Document_B',
'requester_name' => 'Requester_Y'
),
(int) 2 => array(
'id' => '213'
'submission_date' => '2012-07-09'
'name' => 'Document_C',
'requester_name' => 'Requester_X'
),
)
I can't seem to figure it out after going through the 2.0 CakeBook and on StackOverflow...
Any help would be appreciated? Sorry - I'm still a n00b with CakePHP (but REALLY loving it so far!) Thanks!
You need to do a find('all') instead of a find('list') and you can use the fields key like you already are to limit the amount of info that's returned.
It won't come back exactly as you need the data, each field will be in a key of the model it belongs to - if you really need it in that format you can get away with using a virtual field, a custom find, or an afterFind callback to modify the data.
Find list is generally for an id => label formatted array.
You can try this:
$documents = $this
->Document-
>find('all',
array(
'fields' => array('Document.name', 'Requester.name', 'Document.submission_date'),
'joins' => array(
'table' => 'requesters',
'alias' => 'Requester',
'type' => 'left',
'conditions' => array('Requester.id = Document.requester_id')
)
)
);

Resources