I have Users and Courses.
I have a users table, and a courses table.
I also have a course_memberships table with id |
course_id | user_id
I have the appropriate hasmany relationship
for courses and users to relate to CourseMembership
But I have no idea how to create that relationship using a button on the front end. Something like a public function register() on the Courses controller that would put the Auth User ID in the user_id field, and the course id in the course_id field to form the relationship.
I know it was a wall of text, but I figured a description of the issue may be more helpful than an endless scroll of code.
Can anyone help?
You should create a method to save to the CourseMembership model within the Courses Controller. Something like this would work.
public function register($course_id){
$user_id = $this->Auth->user('id');
$data = array(
course_id => $course_id,
user_id => $user_id;
);
if($this->Courses->CourseMembership->save($data)){
$this->Session->setFlash('Registered');
$this->redirect($this->referer());
}
else{
$this->Session->setFlash('Could not register');
$this->redirect($this->referer());
}
}
This way, when people go to /Courses/register/1, it would register them for the course with the ID of 1.
Then when you do a find on the User, the data would be in $user['CourseMembership']
Related
I'm trying to implement a blog type website where the user can rate the posts. So the relationship is like this:
Blog -> blog_links; To Many fk = blog_id
User -> blog_links; To Many fk = user_id
I've tried these solutions and each time get a different error:
User::hasManyThrough(Blog::class, BlogLink::class);
That didn't work, so I tried query scope:
scopeWithLinksAndResorts($query) {
return $query->with(['resorts' => function($q) {
$q->ordered()->withLinks();
}]);
}
That doesn't seem to return any results. So I'm not sure what I'm doing wrong here. And here's a table example:
blogs
id Title Text
1 Test This is a test blog
users
id email
1 test#test.com
blog_links
id blog_id user_id rating
1 1 1 4
Now from this I want to get the blogs the user has rated and their rating. But as I said I get no results. Anyone able to help?
In your User model define the blog's relation
/**
*
*/
public function blogs()
{
return $this->belongsToMany('App\Blog', 'blog_links', 'user_id', 'blog_id')->withPivot('rating');
}
Then in your Blog model define the user's relation
/**
*
*/
public function users()
{
return $this->belongsToMany('App\User', 'blog_links','blog_id', 'user_id');
}
To get all users with their blogs and rating you can do \App\User::with('blogs')->get()
I'm not sure if this is what you want but hope it helps.
I have a Block model which is basically for blocked users. It has a target_id and a sender_id, both of which are IDs from the users table. How can I add data to this pivot table when a user wants to block another user? What should my relationship methods look like?
Since both target_id and sender_id are fields from the users table, your relationship must be defined this way.
class User {
public function blocks() {
return $this->belongsToMany('App\User','blocked_users','sender_id','target_id')->withPivot(['id']);
}
public function blockedBy() {
return $this->belongsToMany('App\User','blocked_users','target_id','sender_id')->withPivot(['id']);
}
}
Here blocked_users is the name of the table.
So, to block a user you can do :-
//User who is going to block
$user = User::find($id);
$inputs = [$target_user_id];
$user->blocks()->attach($inputs);
//or you can use,
$user->blocks()->sync($inputs, false);
The false in the above sync is used when the old synced rows are ignored and new ones are attached.
To get the list of users who that particular user has blocked, you can do :-
$user = User::find($id);
$user->blocks;
And to get the list of users who that particular user is blocked by
$user = User::find($id);
$user->blockedBy;
Thanks,
I've got three models: users, groups and user_groups
users table: id | alias | password ...
groups table: id | name ...
user_groups table: id | user_id (fk users table) | group_id (fk groups table) ...
In my groups controller, I receive data about available groups and the member:
public function edit($id)
{
if (!$id) throw new NotFoundException(__('Unknown Group'));
//All available groups with members
$group = $this->Groups->find('all', [
'contain' => 'Users'
]);
//Only the group + members with the requested id
$member = $this->Groups->get($id, [
'contain' => 'Users'
]);
if (!$group) throw new NotFoundException(__('Group does not exist'));
if ($this->request->is(['post', 'put'])) {
$this->Groups->patchEntity($group, $this->request->data);
if ($this->Groups->save($group)) {
$this->Flash->success(__('Group successfully updated'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Failed to update group'));
}
$this->set('group', $group);
$this->set('member', $member);
}
I'm trying to build a view containing two selectboxes, one for the users that are already member of the group and one for the remaining (not members) users.
When it comes to data saving to the relation model (user_groups) I'm totally helpless.
Do I have to use specific variable names / input field names?
How to serve the data so the controller knows where to save it?
Thanks in advance and sorry for that noob questions, I'm new to the whole framework thing.
I've been learning laravel for a few days now and I was hoping you guy's could help me.
I have the following table structure:
users
------
id
companies
------
id
company_user
------
company_id
user_id
owner
My User and Company models have functions specified like this:
User Model
public function companies() {
return $this->belongsToMany('App\Company', 'company_user', 'company_id', 'user_id')->withPivot('owner');
}
Company Model
public function users() {
return $this->belongsToMany('App\User', 'company_user', 'company_id', 'user_id')->withPivot('owner');
}
For example when I save a company to a user like this:
User::find(1)->companies()->save(\App\Company::find(1));
The pivot table gets filled nicely, but the owner column doesn't get filled.
I can't find many online how to fill this column. Hope you guys can help me?
Thanks in advance!
You can pass additional data as second argument to save():
User::find(1)->companies()->save(\App\Company::find(1), ['owner' => 'foo']);
I'm using the Yii framework and have come across an issue whilst building a Friend/Connection style system. I have a standard users table and to store friends I have a friends table with the following layout (the appropriate FKs etc have been set up):
id | userId | friendId | and some other fields...
As the "friend" is mutual - so, if user A is a friend with user B, then user B is a friend with user A - therefore there is only ever one entry per "friendship".
What I'm trying to do is use Yii's relational query to eventually return items which belong to friends. Currently I have the following relation in the User model...
'friends' => array(self::HAS_MANY, 'UserFriend', 'userId'),
However that only returns 'friends' if the user's ID is present in the userId field. If the user's ID is in the friendId field then the "friendship" won't be recognised.
Is there a way to query using "OR" - for example: if user's ID == userId OR user's ID == friendId then return that entry?
In addition, is there a way to get Yii to return the other ID, so if user's ID == userId it will return friendId, else if user's ID == friendId it will return userId?
I'm eventually trying to do something like:
$userModel = User::model()->findByPk(Yii::app()->user->id); // user's model
$userFriends = $userModel->with(items)->friends; // return friends with their items
Hopefully I haven't confused too many! Sorry for the poor explanation
Thanks :)
Follow the instructions here on creating a database command object, and then you can query with an OR condition as follows:
$command->where(array('OR', 'userID = :userID', 'userID = :friendID'), array(':userID' => $userID, ':friendID' => $friendID));
Do you want get all friends of current user of your app?
You can use CDbCriteria and method find(). Something like this:
$criteria = new CDbCriteria;
$criteria->addCondition('id = :userid');
$criteria->addCondition('friendid = :userid', 'OR'); // OR - the operator to join different conditions. Defaults to 'AND'.
$criteria->params = array(':userid' => Yii::app()->user->id);
$userFriends = UserFriend::model()->find($criteria);
But I'm not sure in your User and UserFriend models structure and mutual relations. Have you some relation from UserFriend to User? If so, than you can use something like $userFriends->user0 after code above.
CDbCriteria details
find() method details