Php 没有关系的负载模型似乎是不可能的
在谷歌搜索和用头撞桌子几个小时后,我仍然无法以我想要的方式解决各种各样的关系查询问题 问题:我在文章和评论以及评论和回复之间有一对多的关系,这很好。在一种情况下,我只想得到评论+回复,而不想加载与文章的反向关系。如何实现这一目标 我已经放弃了从与某条评论相关的文章中加载特定单元格的最初努力。这似乎更不可能 是我的想法错了还是这里有什么问题 以下是模型: 第条:Php 没有关系的负载模型似乎是不可能的,php,mysql,laravel-4,eloquent,Php,Mysql,Laravel 4,Eloquent,在谷歌搜索和用头撞桌子几个小时后,我仍然无法以我想要的方式解决各种各样的关系查询问题 问题:我在文章和评论以及评论和回复之间有一对多的关系,这很好。在一种情况下,我只想得到评论+回复,而不想加载与文章的反向关系。如何实现这一目标 我已经放弃了从与某条评论相关的文章中加载特定单元格的最初努力。这似乎更不可能 是我的想法错了还是这里有什么问题 以下是模型: 第条: class Article extends Eloquent{ protected $table = 'articles';
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附加任何内容
谢谢。不可能是什么,你不知道吗?;)写下问题是什么,因为你的想法肯定是错误的,你如何尝试:1获得评论+回复(无关紧要,除非你想对你说的话做些别的),2当然可以,你如何尝试,3你如何尝试获得评论?无关紧要?真正地当然,首先编辑你的问题,准确地描述你需要什么,因为获取一条没有任何附加内容的评论确实是微不足道的。我很想用雄辩的语言帮助你,但首先我需要知道你想要什么。我完全不知道如何才能更具体地描述我想要什么。1) 按注释ID获取注释+回复(无其他内容)2)按注释ID获取注释+回复+相关文章中的特定单元格3)按注释ID获取注释(无其他内容)。已经这么做了。它返回评论+所有回复+整个相关文章。2.与3基本相同。1.身份证在哪里?我希望ID1的评论+回复更正为1条评论,2条和3条-你怎么说它会返回所有关系?有没有可能不打$comment->article或$comment->repress?我接受了你的回答,并解决了我的问题。在调用Comment::find($commentID)之后,我在下面的某个地方调用了$Comment->article->title,但我不知道这样会将整篇文章填充到$Comment对象中。一定要检查并理解这一点,因为这是避免n+1db调用的必要条件。
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