基于laravel中的数据透视表检索数据

时间:2014-11-29 09:57:28

标签: database laravel-4 pivot eloquent

我的数据库中有这些表

翻译

  1. ID
  2. translation_key_id
  3. 含量
  4. 语言

    1. ID
    2. 代码(它将是" eng"或" ger"或" fre")
    3. TRANSLATION_LANGUAGE

      1. ID
      2. translation_id
      3. LANGUAGE_ID
      4. 现在模型

        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"

        的数据

        我该怎么做?

2 个答案:

答案 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();