vendredi 29 juin 2018

Get relationship based on field value

I have a Model NewsCategory that contains 2 relationship (it may contain more in the future) NewsCategory model belongs to a News model, and the idea is to apply a filter to the News based in the category that the user selected or just fetch "all" the news, the problem is that the NewsCategory relationships belongs to different tables that each have its own purpose.

So in my NewsCategory model i want to access the relationship using the field table_id and a type that tells me if it is a headquarter or a program, so my model is

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class NewsCategory extends Model
{
    //
    public function headquarters()
    {
        return $this->belongsTo('App\Models\Headquarter','table_id');
    }
    public function programs()
    {
        return $this->belongsTo('App\Models\Program','table_id');
    }
}

The problem comes when i do not filter by the relationship and i want to get something like this.

$noticia = Noticia::with('titles')
->with('descriptions')
->with('images')
->with(['categories' => function($categories){
    //i want to get the relationship based on the type of the NewsCategory
    //so when printing i can tell wich category it belongs based it the relationship exists
    switch($categories->type){
        case 'headquarter':
            $categories->with('headquarters');
            break;
        case 'program':
            $categories->with('programs');
            break;
        ....
    }
}])
->get();

But this give an error where Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$type

So how could i make this happends? i have tried putting the type in the News model insted of the NewsCategory but i dont know how to access the parent field inside the relationship function.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire