I have two different tables 'users' and 'users_details'. And made two different models 'User' and 'UserDetail'.In user_details table i have user_id and image fields.But I want to validate image field from users controller using cakephp rule.So please give me any idea to do this task as soon as possible.
Thanks.
Try this if UserDetail is your model into the controller:
$this->loadModel('UserDetail');
if ($this->UserDetail->validates()) {
// it validated logic
} else {
// didn't validate logic
$errors = $this->UserDetail->validationErrors;
}
Because UserDetail has "user_id", therefore it should be setup to belongTo User, and User should either hasMany or hasOne UserDetail. You can find out how to set up relationships in the manual http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html
Then in your Users controller you can access the UserDetail model like such
$this->User->UserDetail->set($this->request->data);
if($this->User->UserDetail->validates()) {
// ...
}
Saving Related Model Data: http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-hasone-hasmany-belongsto
Validation Data From Controller: http://book.cakephp.org/2.0/en/models/data-validation/validating-data-from-the-controller.html
Related
rI am new to laravel 7 and I still have a few small difficulties.
I have two tables: users and services. These two tables have a relation to retrieve a user's service.
$users= User::with('poseur')->get();
It returns all users even those who do not meet the conditions of my relationship.
I use scope in service model:
public function scopePoseurs(){
return $query->whereRaw('slug','pos')
}
And i use belongsTo relation in user model :
public function poseur(){
return $this->belongsTo('App\Service')->poseurs();
}
Exemple: we hase 2 users:
first: Daniel have service slug = 'pos',
second: Patrick have service slug ='dev'
When i use $users=User::with('poseur')->get();, i see Daniel and Patrick.
While there should be only Daniel.
Can you help me understand ?
Thanks !
with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models.
If you want to return all user, that has relation with poseur only, then use has() method :
$users= User::has('poseur')->get();
Ther is also a method called whereHas(), which allows you to specify additional filters for the related model to check :
$users = User::whereHas('poseur', function($q){
$q->where('created_at', '>=', '2020-01-01 00:00:00');
})->get();
I have 2 tables, users and profiles,
and profiles has a field named graduated.
I want to show other users.name who's profile, graduated record as same as logged in user's profile.graduated
I'm new and the only think i know about calling logged in user is $this->Auth->user('id');
when we want to automatically put user's id in the form of adding a new record in a table related to user
Make association with Users and Profiles and then use this:
$users_list = $this->Users->find()
->where(['Profiles.graduated' => $this->Auth->user('graduated')])
->contain(['Profiles'])
->all();
You'll get all users in $users_list
if you have Users belongsTo Profiles relationship
$query=$this->Users->find()->innerJoinWith('Profiles', function ($q) {
return $q->where(['Profiles.graduated' => $this->Auth->user('graduated')]);
});
$query->toArray();
I'm trying to write a small expenses cake app. Basicaly I have a expenseClaim that hasMany Expenses (expense belongsTo expenseClaim). When you add/edit a expenseClaim I want to be able to add multiple expenses for that expense claim from within that view. Could someone point me in the right direction?
Any tutorials / sample code would be massively appreciated. Thanks in advance
using cake 2.1
Put in expenseClaim/add:
$this->expenseClaim->Expense->create();
It should work if the relationship is well set in the model.
If not,
$this->loadModel('Expense');
$this->Expense->create();
should always work.
Edit:
$data=array
(
[Expense] => Array
(
[fieldname1] => 'value'
[fieldname2] => 'value'
)
)
$this->loadModel('Expense');
$this->Expense->create();
if ($this->Expense->save($data)) {
$this->Session->setFlash(__('Done.'));
} else {
$this->Session->setFlash(__('Failure.'));
}
Edit2: if you want to pass data from the view:
if ($this->request->is('post')) {
$this->loadModel('Expense');
$this->Expense->create();
if ($this->Expense->save($this->request->data)) {
$this->Session->setFlash(__('Done.'));
} else {
$this->Session->setFlash(__('Failure'));
}
}
The request is created automatically if you use the form helper in the view.
Can I use the $this->ModelName->AssociatedModel->save($this->data) to save only the related data?
If not - what are my options?
The data structure is:
$this->data['AssociatedModel']['field_a'] = 'some value';
$this->data['AssociatedModel']['field_b'] = 'some other value';
well, I landed here with a User HABTM ROLE usecase where the User table is a read-only db view.
The accepted solution didn't worked for me on cake2.x
In the end I settled on the following AppModel method:
public function saveHabtmOnly($data, $parent_id) {
$this->_saveMulti($data, $parent_id, $db=$this->getDataSource());
// _saveMulti has no failure signaling
// probably just throws Exception
return true;
}
where
$data = array('Role'=>array(...));
and $parent_id is the id of the User
Yes, you can save associated data like that.
got this situation. Reports habtm users. So Im trying to paginate just the Reports that are linked to the Auth user... I read when you have a habtm relationship you have to bind the model temporarily using 'hasOne' like this:
function index(){
$conditions=array('ReportsUser.user_id'=>$this->Auth->User('id'), 'ReportsUser.report_id'=>'Report.id');
$this->beforeFind();
$this->Report->recursive=0;
$this->set('reports',$this->paginate($conditions));
}
function beforeFind()
{
$this->Report->bindModel('hasOne'=>array('ReportsUser'), false);
}
so here is the issue... that doesn't work...
that give me no results... I already checked the database for user having any Report, and i logged in with one of those user...
any suggestions?
GOT IT!!
$conditions=array('ReportsUser.user_id'=>$this->Auth->User('id'), 'ReportsUser.report_id'=>'Report.id');
i just had to remove 'ReportsUser.report_id'=>'Report.id' cuz cake was searching for it for a second time... so i just left
$conditions=array('ReportsUser.user_id'=>$this->Auth->User('id'));
and i add
$this->Report->bindModel('hasOne'=>array('ReportsUser'**=>array('className'=>'ReportsUser', 'foreignKey'=>'report_id')**), false);