Retrive data based on pivot table in laravel

moin khan

I have those tables in my database

Translation

  1. id
  2. translation_key_id
  3. content

Language

  1. id
  2. code (it would be "eng" or "ger" or "fre")

translation_language

  1. id
  2. translation_id
  3. language_id

Now the models are

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');
    }
}

Now i want to retrieve those data which have transkation_key_id = abc (as for example ) and also with code = "eng"

How can i do that?

Jarek Tkaczyk

First of all I don't see the need for pivot table here.

Show me why you need that, or change your relation to belongsTo. You can link translation with language using id (1) or code (2), which is unique obviously, right? So here it goes:

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

then

// 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();

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related