我有一个 self 引用表,其中包含新闻及其各自的翻译。我要做的是查询每个父新闻的翻译语言,以显示在我的索引新闻页面中。 在索引新闻页面中,我有一个表格,其中显示了我所有的父新闻:
- 标题
- 家长新闻语言
- child 新闻语言(翻译)(这是我的问题!)
- 编辑
- 删除
有了这个,我想自动查看新闻的原始语言,并检查它是否已经被翻译过。
我的代码是这样的:
表格
语言
- 编号
-代码
新闻
- 编号
- parent_id
- lang_id
- 标题
- body
模型
语言.php
class Language extends Eloquent {
public function news() {
return $this->hasMany('News');
}
}
新闻.php
class News extends Eloquent {
protected $table = 'newss';
public function language() {
return $this->belongsTo('Language','lang_id');
}
public function parent_news() {
return $this->belongsTo('News','parent_id');
}
public function child_news() {
return $this->hasMany('News','parent_id');
}
}
有谁知道如何查询这样的东西吗? 我认为这可能不是检查翻译的最佳解决方案,因此如果有人有任何简化此想法的建议,我将非常高兴收到您的来信。
谢谢,
最佳答案
class News extends Eloquent {
protected $table = 'newss';
function newss(){
return $this->hasOne('News', 'parent_id');
}
文档说,对于自连接,使用 hasOne
方法。
然后:
News::find($news->id)->news()->whereRaw('parent_id= parent_id')->get();
关于mysql - Laravel - 查询自引用表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23545742/