I'm looking for the best practice for adding an id to a database table. As an example I have a Member (model) that hasMany Recipe. The Recipe model states that it belongsTo Member:
public $belongsTo = array(
'Member' => array(
'className' => 'Member',
'foreignKey' => 'member_id',
)
);
I hoped that this would be sufficient when saving new recipes to the database, but I see that cake cannot figure out the relationship on its own because I am getting an error ("General error: 1364 Field 'member_id' doesn't have a default value") when using add:
public function add() {
if ($this->request->is('post')) {
$this->Recipe->create();
if ($this->Recipe->save($this->request->data)) {
$this->Session->setFlash(__('The recipe has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The recipe could not be saved. Please, try again.'));
}
}
}
Now, in this case I can easily get around the problem by adding
$this->request->data['Recipe']['member_id'] = $this->Auth->user('id');
but in general the ids that I will want to add will not be stored with the Auth data. So I would like to know how to access the id when saving something that belongsTo something else.
edit: I think my question was probably not worded well enough. I will restate what I'm looking for:
Say User hasMany A, which hasMany B, which hasMany C. C belongsTo B, A, and User (table for C contains user_id, a_id, and b_id). A user logs in, and picks a certain A, and then a certain B. The user now wants to add a new C. What is the best way to get all the id values for the new C entry? Do I just set a bunch of session variables? Should they all be passed in the URL? Is there some better way?
You need to provide any information that you want to save in the database. This means you either use the Auth information like you already stated or you get the information via a form where you can select from all the members available.
Either way the information has to come from somewhere. It can not create itself out of nothing.
If the user is selecting or picking A, B or C, them, somehow you can store their data and deal with them.
Usually, the common way is using forms. If you are using Javascript, you can set hidden inputs or if you are using AJAX, just using them inside it to call the final Cake functions.
You have to see how the user picks them, and then, store that ID in some variable to play with it. POST, GET, SESSIONS, COOKIES...
Related
I have a Users table and a Roles table.
A user has one role. So in UsersTable.php:
$this->belongsTo('Roles', [
'foreignKey' => 'role_id',
'joinType' => 'INNER',
]);
Now in User.php (Entity!!) I need the role name of the users role.
But I have only the User Entity in which is no associated data.
I now have:
public function getRole()
{
$q = TableRegistry::getTableLocator()->get('Roles');
$roles = $q->find('list')->toArray();
return $roles[$this->role_id];
}
This works, but TableRegistry is marked obsolete in cake4, and I can't find any other way the make this work. What is the propper way of doing this?
If you want to use both the User and Role data in a controller you can just do for example
$user = $this->Users->get($id, [
'contain' => ['Roles'],
]);
and the resulting object has $user->role defined as a Role entity.
However, I have a feeling you already know this and have another issue that may or may not overlap with a problem I was solving just recently. Check out ndm's answer to my question here and hopefully it helps you! CakePHP 4.1 User entity as authorization identity associated fields
Apologies if that's not your scenario, I just found this current thread while looking for an answer to my problem, and it was definitely the closest to my own issue.
There is a problem when I write an add() function for UsersController.
public function add() {
if ($this->request->is('post')) {
$this->request->data['User']['book_id'] = $this->Book('id');
if ($this->User->saveAssociated($this->request->data)){
$this->request->data['User']['book_id'] = "ff";
$this->Session->setFlash(__('Save User'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('User Error.'));
}
}
If I add a User I want to save the book ID in my User book_id.
Anyone know how to deal with this problem? Thanks!
When you're adding a new user, does he get to select a book from a drop down(in the form)? If so, $this->request->data['User']['book_id'] will already contain the Book id.
There's no need to explicitly write $this->request->data['User']['book_id'] = $this->Book('id'); like you have done.
The way I see it, the add.ctp view file should contain a select box containing a list of all books which the user can select. On selecting one of those and submitting the form, $this->request->data['User']['book_id'] will automatically store the book_id, without having to write anything in the controller.
Please specify the add.ctp form fields so that I can assist you better.
Thanks!
I have two main tables:
Books (id, author, isbn, ...)
Users (id, username, password, ...)
I am looking at building an application, wherein User1 logs in and can:
view list of all books (eg. only title)
view details (author, isbn, ...) of only certain books that he should have access to
Each user may have access to a certain set of books. I don't need various roles.
I have setup the MVC and the relationships (habtm) for the above. I am now looking at developing the permissions. Do you think the CakePHP ACL solves this problem or is it overkill?
If it is overkill, is there another component or easier way to build the desired functionality?
Yes, ACL is overkill
ACL is a very powerful and flexible system - but it doesn't come free it brings with it complexity. Unless you have a usecase where you absolutely need fine-grained permissions (the two rules you've described do not fit this) - don't use ACL.
Restricting to books a user he has added
This rule is easy to implement - e.g. add to relevant find calls:
$results = $BookModelInstance->find('all', array(
'conditions' => array(
'created_by' => AuthComponent::user('id')
)
));
Restricting to books a user he has bought
This rule is also easy to implement, thought slightly more involved:
$BookModelInstance->bindModel(array(
'hasOne' => array( // Yes, hasOne not hasMany
'MyPurchase' => array(
'className' => 'Purchase',
'foriegnKey' => 'user_id'
)
)
));
$results = $BookModelInstance->find('all', array(
'recursive' => 0, // to join hasOne+belongsTo associations into the query
'conditions' => array(
'MyPurchase.user_id' = AuthComponent::user('id'),
)
));
The bindModel call achieves the equivalent of SELECT .. FROM books LEFT JOIN book_users.. The conditions in the find call will therefore restrict results to books where there is a record of the user purchasing the book.
Putting them both together
A simplistic implementation of automatically applying both these rules would be:
model Book extends AppModel {
public $actsAs = array('Containable');
public $restrictToUser = true;
public function beforeSave($options = array()) {
if (!$this->id) {
// Store who created this book
$this->data[$this->alias]['created_by'] = AuthComponent::user('id');
}
return true;
}
public function beforeFind($queryData) {
if (!$this->restrictToUser) {
// we don't want to apply user-level restrictions
return true;
}
$userId = AuthComponent::user('id');
if (!$userId) {
// we want to restrict to the current user - there isn't one.
return false;
}
// define the association to the purchase table
$this->bindModel(array(
'hasOne' => array(
'MyPurchase' => array(
'className' => 'Purchase',
'foriegnKey' => 'user_id'
)
)
));
//ensure the purchase table is included in the current query
$queryData['contain']['MyPurchase'] = array();
// restrict to rows created by the current user, OR purchased by the current user
$queryData['conditions']['OR'] = array(
$this->alias '.created_by' => $userId,
'MyPurchase.user_id' => $userId
);
return $queryData;
}
}
This requires a field created_by (or equivalent) to be in the books table, and uses containable to ensure that the purchases table (or equivalent) is included in all relevant queries.
Most simple solution: Add a condition in your controller, so:
$this->set('books', $this->Book->find(
'all',
array('conditions' => array('Book.user_id' => $user['User']['id']))
);
Disadvantages: You will likely create duplicate code here since this check has to happen also in other places. Also when you start testing your model you can only test that it returns books, you cannot test a model method like: getMyBooks($userId). So no, not the preferred solution.
Next solution: Check in the model
It could be done by a check in for example your books model. You could just check in the afterfind() method whether the returned records are allowed or not. In your beforefind you could also add an additional condition to all queries.
In general a model should be fat so I would suggest implementing clear methods there like: getAllBooks, getBooksOfUser($User), getLatestBooksOfUser($User) etc.
Why is this a nice implementation? Because you now manage the access levels in a central place. You can test the model and you are sure it does only return books from this user.
With beforeSave etc. you can intervene every save attempt and first check: hey, you want to save this but is this really your book?
ACL solution
But in general it could be wise to implement some ACL solution (preferably the built in one) since that makes you application much more future proof. It allows flexibility, for example:
Each user may have access to a certain set of books. I don't need various roles.
That's true for now but the future can change it. So if you need a quick solution just custom filter the records. But think about the future.
I'm trying to implement a hasone relationship between 2 models, but I can't have the 'add' form autocomplete with the possible options in the second model (the one that belongsTo the first one). This is my code:
- model 1: item.php
<?php
class Item extends AppModel{
var $name = 'Item';
var $primaryKey = 'id';
var $hasOne = 'CoverImage';
}
?>
- model 2: cover_image.php
<?php
class CoverImage extends AppModel{
var $name = 'CoverImage';
var $primaryKey = 'id';
var $belongsTo = array(
'Item' => array(
'className' => 'Item',
'foreignKey' => 'item_id'
));
}
?>
- add view of model 2: add.ctp
<?php echo $this->Form->create('CoverImage',array('url' => array('controller' => 'admins', 'action' => 'add')));?>
<fieldset>
<legend><?php __('Info'); ?></legend>
<?php
echo $this->Form->input('item_id');
echo $this->Form->input('description');
?>
</fieldset>
<?php echo $this->Form->end(__('Create', true));?>
For what I see in Cake's documentation, with this relationship, in the add view I should see a dropdown list in the item_id field to be able to select to which item does this CoverImage belongs to, but the dropdown is empty (and yes, I have some items in the items table already).
Maybe I'm missing something or I've done something wrong, but I can't figure it out. Thanks so much in advance for any clues!
EDIT
One think I've just realized is that if I do this:
echo $this->Form->input('item_id', array('type'=>'text'));
instead of this:
echo $this->Form->input('item_id');
I can add/edit the *item_id* field, I can see its value in the text box. However, if I leave the other one, I just see an empty dropbox and when I try to add/edit a CoverImage, it doesn't work, it just shows an empty white page, not even with errors...
Maybe this is a lead to something...
In order for that to work you have to create a list of possible options in the controller. That does not happen automatically.
public function add() {
$items = $this->CoverImage->Item->find('list');
$this->set(compact('items'));
}
The FormHelper only automatically infers that the field item_id should be populated by the options in the variable $items (plural, no _id).
Do be careful that Items that already haveOne CoverImage should not be part of that list. find('list', array('conditions' => array('CoverItem.id' => null))) will probably* take care of that, but you'll need to recheck just before saving as well, or you need to rethink your associations.
* Not sure off the top of my head whether that'll work for 'list' searches.
EXCELLENT QUESTION. You've run afoul of a disingenuous feature of Cake's associations:
Considering you defined the relationship as hasOne? Guessing at the trace but Cake probably even correctly inferred your preference for list functionality. You got your automagic list...
...of One.
$hasOne is pretty exclusive like that. It "uses up" those "has" relationships (it's makes the relationship a de facto Singleton - so Users only have 1 Profile <-> Profile only has 1 User). Consider - Database can have many configurations, but Dbo will only ever have one Connection at a time and Connection will only have one Dbo. Thus -> hasOne is for marrying two Models til die() do they part.
-- So it doesn't get used nearly as much as hasMany and belongsTo.
For your purpose, you probably want to change to a different association.
Adding an additional $this->Item->find doesn't really fix what's wrong (and I wouldn't recommend it, unless you're mostly done with both models/controllers, or you actively want things to start getting weird fast.)
Also, changing how you call the Form Helper methods - if you return a 'list' type fetch from a find, Cake will automatically produce an option list out of it. What's actually happening is, you're sneaking around your Model on a very thin margin of View functionality. That's why specifying the input type to "break the magic" tends to be discouraged (which, you totally can if you want. Just understand what's actually happening, or: see, weird, fast.)
But you might want to rethink how you've associated your models - wouldn't it also be correct to say, each Item belongsTo a CoverImage (same as each CoverImage belongs to an Item) -- because you have a form expressly permitting a CoverImage to select an Item, any Item, to be displayed with? You'll probably get better results.
HTH. :)
I'm having trouble with my HABTM relationship in CakePHP.
I have two models like so: Department HABTM Location. One large company has many buildings, and each building provides a limited number of services. Each building also has its own webpage, so in addition to the HABTM relationship itself, each HABTM row also has a url field where the user can visit to find additional information about the service they're interested and how it operates at the building they're interested in.
I've set up the models like so:
<?php
class Location extends AppModel {
var $name = 'Location';
var $hasAndBelongsToMany = array(
'Department' => array(
'with' => 'DepartmentsLocation',
'unique' => true
)
);
}
?>
<?php
class Department extends AppModel {
var $name = 'Department';
var $hasAndBelongsToMany = array(
'Location' => array(
'with' => 'DepartmentsLocation',
'unique' => true
)
);
}
?>
<?php
class DepartmentsLocation extends AppModel {
var $name = 'DepartmentsLocation';
var $belongsTo = array(
'Department',
'Location'
);
// I'm pretty sure this method is unrelated. It's not being called when this error
// occurs. Its purpose is to prevent having two HABTM rows with the same location
// and department.
function beforeSave() {
// kill any existing rows with same associations
$this->log(__FILE__ . ": killing existing HABTM rows", LOG_DEBUG);
$result = $this->find('all', array("conditions" =>
array("location_id" => $this->data['DepartmentsLocation']['location_id'],
"department_id" => $this->data['DepartmentsLocation']['department_id'])));
foreach($result as $row) {
$this->delete($row['DepartmentsLocation']['id']);
}
return true;
}
}
?>
The controllers are completely uninteresting.
The problem:
If I edit the name of a Location, all of the DepartmentsLocations that were linked to that Location are re-created with empty URLs. Since the models specify that unique is true, this also causes all of the newer rows to overwrite the older rows, which essentially destroys all of the URLs.
I would like to know two things:
Can I stop this? If so, how?
And, on a less technical and more whiney note: Why does this even happen? It seems bizarre to me that editing a field through Cake should cause so much trouble, when I can easily go through phpMyAdmin, edit the Location name there, and get exactly the result I would expect. Why does CakePHP touch the HABTM data when I'm just editing a field on a row? It's not even a foreign key!
From the CookBook the 1st problem is:
By default when saving a
HasAndBelongsToMany relationship, Cake
will delete all rows on the join table
before saving new ones.
I am not quite sure why Cake is trying to save the HABTM data even though you don't have a foreign key in your data, but there is an easy solution for that. Simply destroy the association for the save call:
$this->Location->unbindModel(
array('hasAndBelongsToMany' => array('Department'))
);
I'm thinking of one reason why this might be happening. When you retrieve Location, you also retrieve locations_departments data. And when you do a save($this->data) it looks for models in the array and saves them.
A way to solve this is setting the recursive attribute (of a model) to -1 or 0 (try, I'm not sure, just print out the data to see what comes out). You can set it in the model: var $recursive = -1; or in the controller method (action): $this->ModelName->recursive = -1;
More about recursive: http://book.cakephp.org/view/439/recursive
It's really similar to what harpax suggested, just if you don't need that data, tell it to Cake, so that it won't fetch it.
Trouble is that when saving your Location, you gave the save method an array containing all the DepartmentsLocations too. Thus CakePHP destroys everything and try to recreate it.
This is a common mistake with cake since it will often pull far too many results for you.
Be sure to pass only the data that needs to be saved, or better to fetch only the datas you need.