vendredi 20 mars 2020

Return default value if belongTo relation is returned null

I have a belongTo relation, if join condition is matched then ok but when there is no data for this it returns null. In this case, I want it returns default value as I expected. This is what I try but it not success. Please help me?

class Task extends Model
{
    use SoftDeletes;

    protected $table = 'tasks';
    protected $fillable = [
        'name',
        'description',
        'project_id',
    ];
    protected $with = ['project', 'status'];

    // this is expected
    public function getProjectAttribute($value)
    {
        return $value ?? ['id' => '', 'name' => ''];
    }

    /**
     * @return App\Modules\Com\Models\Project
     */
    public function project()
    {
        return $this->belongsTo(Project::class, 'project_id', 'id')->select(['id', 'name']);
    }
}

With description attribute, I can override it but why I dont the same thing with project attribute? And how do I set where for project relation?

Like this Task::select(*)->project()->where('project.name', 'ABC');.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2QySqgW
via IFTTT

Aucun commentaire:

Enregistrer un commentaire