I'm trying to join my comment table with my user table like this comment.userId=user.id
unfortunately when i print_r($this->user); i get nothing. what am i doing wrong here?
in my comment model
public function relations()
{
return array(
'user' => array(self::BELONGS_TO, $this->module->user, 'userId'),
);
}
public function getLastName()
{
print_r($this->user);
die;
return is_null($this->user) ? '' : $this->user->{$this->module->lastNameAttribute};
}
where
$this->module->user = 'User'; //User is the model name
and
$this->module->lastNameAttribute = 'last_name';
in my view
$comments = $model->getCommentDataProvider();
$comments->setPagination(false);
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$comments,
'itemView'=>'application.modules.comment.views.comment._view', //view file location
'emptyText' => '<div class="alert alert-info">No comments yet.</div>',
'summaryText' => '<h4>'.Yii::t('commentTitle','{n} comment|{n} comments',$comments->totalItemCount).'</h4>'
));
I see a small typo, maybe you mistaken while making a post:
comment.userid=user.id
here it's userid and in relation you referenced it with userId
check it out please
EDIT - after question edit
I'm not familiar with CommentableBehavior but it seems to me that you need to eager load User model with each Comment:
$comments = Yii::createComponent($this->module->commentModelClass)->with('user')->findAll($this->getCommentCriteria());
I added with('user') in getComments() method
Related
How to get the count of childCompetency through childDomain which having has many relation
'childDomain' => array(self::HAS_MANY, 'SkillRelDomain', 'skill_id'),
'childCompetency' => array(self::HAS_MANY, 'SkillRelCompetency', 'domain_id'),
Here is a one to many (User:Post) relationship example in Yii 1
In case of post every post belongs to a user. So relation looks like this.
public function relations() {
return array(
'user'=>array(self::BELONGS_TO, 'User', 'iduser'),
);
}
Similarly, a user can have multiple posts. So relation for user as:
public function relations() {
return array(
'posts'=>array(self::HAS_MANY, 'Post', 'iduser'),
);
}
Now when you do a $user = User::model()->findByPk($id), you can have access to relation data also
you can call
foreach($user->posts as $post){
echo $post->name;
}
I've created a form which adds a category of product in a Categories table (for example Sugar Products or Beer), and each user has their own category names.
The Categories table has the columns id, category_name, userId, created_At, updated_At.
I've made the validation and every thing is okay. But now I want every user to have a unique category_name. I've created this in phpMyAdmin and made a unique index on (category_name and userId).
So my question is this: when completing the form and let us say that you forgot and enter a category twice... this category exist in the database, and eloquent throws me an error. I want just like in the validation when there is error to redirect me to in my case /dash/warehouse and says dude you are trying to enter one category twice ... please consider it again ... or whatever. I am new in laravel and php, sorry for my language but is important to me to know why is this happens and how i solve this. Look at my controller if you need something more i will give it to you.
class ErpController extends Controller{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('pages.erp.dash');
}
public function getWarehouse()
{
$welcome = Auth::user()->fName . ' ' . Auth::user()->lName;
$groups = Group::where('userId',Auth::user()->id)->get();
return view('pages.erp.warehouse', compact('welcome','groups'));
}
public function postWarehouse(Request $request)
{
$input = \Input::all();
$rules = array(
'masterCategory' => 'required|min:3|max:80'
);
$v = \Validator::make($input, $rules);
if ($v->passes()) {
$group = new Group;
$group->group = $input['masterCategory'];
$group->userId = Auth::user()->id;
$group->save();
return redirect('dash/warehouse');
} else {
return redirect('dash/warehouse')->withInput()->withErrors($v);
}
}
}
You can make a rule like this:
$rules = array(
'category_name' => 'unique:categories,category_name'
);
I am a newbie in CakePHP 1.3... I want to display or show the USER's username instead of USER's id, who post the COMMENTS in the POST view... Anyone can help me please?
Here is the model association I made:
POSTS 'has many' COMMENTS
COMMENTS 'belongs to' USERS
POST->COMMENT->USER
I already read the Containable Behavior of CakePHP 1.3, but still I can't understand it well... Please help me what codes to put in the post_controller's view & view.ctp that can show the related's related table in the POST view.
And How to call the USER's data in the POST view.
I'm still confused.
Thanks in Advance, Azure
Assumptions
You have three tables as below
(1) Posts
* id
* title
(2) Comments
* id
* post_id
* user_id
(3) Users
* id
* name
View Function in PostsController.php file
public function view($id) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$this->Post->recursive=2;
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
$this->set('post', $post);
}
Content of view.ctp file in app/View/Posts/ folder
<!-- File: /app/View/Posts/view.ctp -->
<h1><?php echo 'Post ID : '.h($post['Post']['id']); ?></h1>
<h1><?php echo 'Post Title : '.h($post['Post']['title']); ?></h1>
<?php
echo 'Comments By Users : ';
if(!empty($post['Comment'])){
foreach ($post['Comment'] as $key=>$value){?>
<p>User Name : <?php echo $value['User']['name'];?></p>
<?php }
}
else {
echo '<br/>';
echo 'No Comments Yet';
} ?>
Model File : User.php
<?php
class User extends AppModel {
public $hasMany = array(
'Comment' => array(
'className' => 'Comment',
)
);
}
?>
Model File : Comment.php
<?php
class Comment extends AppModel {
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
)
);
}
?>
Model File : Post.php
<?php
class Post extends AppModel {
public $hasMany = array(
'Comment' => array(
'className' => 'Comment',
)
);
}
?>
I assume you are saving user id in comments table and user names are in users table who posts the comment, then use the below solution
In Controller method:
$userdata=$this->User->find('all',array('fields'=>array('id','username'),'recursive'=>-1));
$userid=Set::extract('/User/id', $userdata);
$username=Set::extract('/User/username', $userdata);
$data=array_combine($username,$userid);
$this->set('name',$data);
In View:
$cid=$var['Comment']['user_id'];
$username=array_search($cid, $name);
echo $username;
i got 2 models: Project and Users connected with (User.php):
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
"projects"=>array(self::MANY_MANY, 'Project','projects_users(user_id, project_id)'),
);
}
I want to show all users in CActiveDataProvider who are not connected with project. How can i do it?
I found solution:
$criteria=new CDbCriteria;
foreach($model->users as $cur) {
$criteria->addCondition("ID != ".$cur->ID);
}
$users=User::model()->findAll($criteria);
$dataProvider2=new CActiveDataProvider('User');
$dataProvider2->data = $users;
Try this:
$users = User::model()->with('projects')->findAll(array(
'together' => true,
'condition' => 'projects.id IS NULL',
));
If I create a comment like this:
$post->comments()->create(array('body' => 'Comment message'));
And I have the model on my post:
public function comments()
{
return $this->morphMany('Comment', 'shared_comments');
}
It fills the polymorphic relationship field between post and comment.
I also have the model on my comment:
public function author()
{
return $this->belongsTo('User');
}
How can I also fill the 'user_id' field in the comment table?
You can just explicitly specify the user id in the array.
$post->comments()->create(array(
'body' => 'Comment message',
'user_id' => Auth::user()->id
));
Alternatively, you could create the comment and then insert the relationship with both the posts and users tables.
$post = Post::find($whatever);
$user = Auth::user()->id;
$comment = Comment::create(array(
'body' => 'Comment message'
));
$post->comments()->insert($comment);
$user->comments()->insert($comment);
In Laravel 4, you would use save($comment) instead of insert($comment) for the last two lines. This is a breaking change from Laravel 3.