mercredi 29 juin 2016

Laravel 5.2 Model Relationships

im new to Laravel and have a relationship question.

The goal is to get all News where news.page_id = page.id AND page.pagetype_id = pagetype.id WHERE pagetype.component = news AND page.app_id = 1

class News extends Model
{
    protected $table = 'news';
    protected $fillable = ['page_id', 'title', 'description', 'active', 'created_at', 'updated_at'];
}

class Page extends Model
{
    protected $table = 'pages';
    protected $fillable = ['app_id', 'unique_id', 'pagetype_id', 'title', 'picture_url', 'short_description', 'description', 'valid_since', 'valid_until', 'extras', 'active', 'created_at', 'updated_at'];

    public function pagetype() {
        return $this->belongsTo('App\Models\PageType', 'pagetype_id');
    }
}


class PageType extends Model
{
    protected $table = 'pagetypes';

    public function page() {
      return  $this->belongsToMany('App\Models\Page', 'pagetypes', 'id', 'id');
    }
}

// now i need   All News Items where page.pagetype_id = pagetypes.id and patchtypes.component = news

// First Attempts are

Page::whereHas('pagetype', function ($q) {
            $q->where('component', 'news');
        })->where(['app_id' => 1])->get();

// result is all Pages which has the proper component news. 

This is what i have tried yet, but in my attempt i'll only receive the proper pages but of course not the news.

My "current" solution is to get all the pages and then loop through News::where('page_id', $myPageId). But im pretty sure its possible to get a proper relationship to get also news.

I cant do any other model since there are many different pagetypes and components aswell.

Thanks so far.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire