1

I have a self referencing table with news and their respective translations as childs. What I'm looking to do is to query the language of the translation for each of the parent news to display in my index news page. In the index news page i have a table where i display all my parent news with:

  • title
  • parent news language
  • child news language (translation) (This is my problem!)
  • edit
  • delete

With this I want to automatically see the original language the news was written in, and check if it has been translated already or not.

My code is something like this:

Tables

Languages
- id
- code

Newss
- id
- parent_id
- lang_id
- title
- body

Models

Language.php

class Language extends Eloquent {

    public function news() {
        return $this->hasMany('News');
    }
}  

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

}

Does anyone know how to query something like this? I believe this might not be the best solution to check for translations, so if anybody has any suggestions to simplify this idea i would be very glad to hear from you.

Thanks,

Rui Silva
  • 99
  • 4
  • 12
  • [This may help](http://heera.it/laravel-model-relationship). – The Alpha May 08 '14 at 15:31
  • 1
    Thanks WereWolf, your article seems a bit overwhelming for me right now but ill try to digest it.. it sure seems interesting for what i'm trying. – Rui Silva May 08 '14 at 16:03
  • ended up changing child_news() to translation() to be more readable. I just needed this in the end @if($news->translations->count()) @foreach($news->translations as $translation) {{ $translation->language->code }} @endforeach – Rui Silva May 08 '14 at 17:22

1 Answers1

0
class News extends Eloquent {
    protected $table = 'newss';
    function newss(){
        return $this->hasOne('News', 'parent_id');
    }

The docs says, that for a self-join, use the hasOne method.

Then:

News::find($news->id)->news()->whereRaw('parent_id= parent_id')->get();
toesslab
  • 5,092
  • 8
  • 43
  • 62