Friday, September 28, 2012

Re: Need help with a find on related HABTM relationship

You don't really need to add a constraint if your code if you specify
the User.id as a condition and run your query on the User model.

In Project model:

public function fetchAll($user_id = null)
{
if (!empty($user_id))
{
return $this->User->find(
'all',
array(
'conditions' => array(
'User.id' => $user_id
),
'contain' => array(
'Project' => array(
'Site'
)
)
)
)
}
else
{
// get all projects
}
}

In ProjectsController, just pass $this->Auth->user('id'). The else
block above would be used for an admin action, or a view that listed
all project names for whatever reason.

On Fri, Sep 28, 2012 at 2:10 PM, Clark Ritchie <clarkritchie@gmail.com> wrote:
> I'm looking for some guidance here.
>
> I have:
>
> User hasAndBelongsToMany Project
>
> Schema:
> Users.id
> Users.name
> ...
>
> Project hasAndBelongsToMany User
>
> Schema:
> Project.id
> Project.name
> ...
>
> My join table:
>
> projects_users.user_id
> projects_users.project_id
>
> Site belongsTo Project
>
> Site.id
> Site.project_id
> ...
>
>
> Users-Projects works OK, I can assign a user to one or many projects.
> Sites-Projects works OK, I can assign a Site to a Project.
>
> Now, I want to make sure the user can only find sites that match the
> projects to which they are assigned. I assume I need to put a condition
> into the Site's beforeFind function, but I can't figure it out.
>
> Any guidance here?
>
> --
> Like Us on FacekBook https://www.facebook.com/CakePHP
> Find us on Twitter http://twitter.com/CakePHP
>
> ---
> You received this message because you are subscribed to the Google Groups
> "CakePHP" group.
> To post to this group, send email to cake-php@googlegroups.com.
> To unsubscribe from this group, send email to
> cake-php+unsubscribe@googlegroups.com.
> Visit this group at http://groups.google.com/group/cake-php?hl=en.
>
>

--
Like Us on FacekBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com.
To unsubscribe from this group, send email to cake-php+unsubscribe@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php?hl=en.

No comments: