问题:我在文章和评论以及评论和回复之间存在一对多的关系,这很好。在一种情况下,虽然我想获得JUST评论+回复而不加载与文章的反向关系。如何实现?
我已经放弃了我最初的努力,希望从与某个评论相关的文章加载特定细胞。这似乎更加不可能。
我的想法是错的还是这里的问题是什么?
以下是模型:
文章:
class Article extends Eloquent{
protected $table = 'articles';
protected $softDelete = true;
protected $fillable = array('short_title','long_title','description','content','zenra_link','source_url','source_title');
public static $rules = array(
'short_title'=>'required|min:5',
'long_title' =>'required',
'description'=>'required',
'content'=>'required'
);
public function category(){
return $this->belongsTo('Category');
}
public function tag(){
return $this->belongsToMany('Tag','tagmaps');
}
public function comment(){
return $this->hasMany('Comment');
}
public function picture(){
return $this->hasOne('Picture');
}
}
注释:
class Comment extends Eloquent{
protected $fillable = array('author','content','published','article_id');
protected $table = 'comment';
public static $rules = array(
'author'=>'required|min:5',
'comment' =>'required|min:10'
);
public function reply(){
return $this->hasMany('Reply');
}
public function article(){
return $this->belongsTo('Article');
}
}
最后但并非最不重要的是回复:
class Reply extends Eloquent{
protected $fillable = array('author','content','published','comment_id');
protected $table = 'reply';
public static $rules = array(
'author'=>'required|min:5',
'comment' =>'required|min:5'
);
public function comment(){
return $this->belongsTo('Comment');
}
}
问题1:如何通过评论ID得到评论+回复?
问题2:如果可能,我可以通过评论ID从文章中获得评论+回复+特定单元吗?
问题3:如果评论ID没有附加任何评论,我如何获得评论?
谢谢。
答案 0 :(得分:0)
3. Comment::find($commentId); // return Eloquent Model with given id
2. // I suggest renaming relation to replies as there are many replies for a comment
$comment = Comment::with('replies') // load related replies
->with('article') // you want a single field, but better load whole article, then fetch what needed
->find($commentId);
// then:
$comment->replies; // Collection of related Reply models
$comment->article->id; // id of related article (or whatever field you want)
1. Comment::with('replies')->find($commentId); // retrieves comment with related replies