我的数据库中有这些表
现在模型
class Language extends Eloquent {
protected $fillable = array('id','code');
protected $table = 'language';
private $rules = array();
public function translation()
{
return $this->belongsToMany('translation','language_translation');
}
}
class Translation extends Eloquent {
protected $fillable = array();
protected $table = 'translation';
private $rules = array();
public function language()
{
return $this->belongsToMany('language','language_translation');
}
}
现在我要检索那些transkation_key_id = abc
(例如)和code = "eng"
我该怎么做?
答案 0 :(得分:0)
您构建的关系不正确
试试这个
class Language extends Eloquent {
protected $fillable = array('id','code');
protected $table = 'language';
private $rules = array();
public function translation()
{
return $this->belongsToMany('Translation','translation_language');
}
}
class Translation extends Eloquent {
protected $fillable = array();
protected $table = 'translation';
private $rules = array();
public function language()
{
return $this->belongsToMany('Language','translation_language');
}
}
答案 1 :(得分:0)
首先,我不认为这里需要数据透视表。
告诉我你为什么需要这个,或者改变你与belongsTo
的关系。您可以使用id
(1)或code
(2)将翻译与语言联系起来,这显然是独一无二的,对吗?所以这就是:
table translations: id, key, content, language_id (or language_code)
// Translation
public function language()
{
// option 1
return $this->belongsTo('Lanugage');
// or 2:
// return $this->belongsTo('Lanugage', 'language_code', 'code');
}t
然后
// option 1
Translation::where('key', 'whatever')->whereHas('language', function ($q) {
$q->where('code', 'eng');
})->first();
// option 2, even easier w/o any join needed
Translation::where('key', 'whatever')->where('language_code', 'eng')->first();