Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

laravel - Laravel6 Eager loading with dynamic OwnerKey in morphTo relation

Hi I'm struggling to get related model with eager loading and dynamic owner key If it is not eager loading works fine but i want to make it eager Is it possible to eager load with dynamic owner key ? Below is what I've done

I'm using Laravel6

Model has taskable relation method

public function taskable()
    {
        $ownerKey = $this->getAttribute('taskable_type') === 'AppModelsTask'
            ? 'task_id'
            : 'id';
        return $this->morphTo('taskable', 'taskable_type', 'taskable_id', $ownerKey);
    }

when call it on each model it works fine

   public function getPlanDetail(int $plan_id)
    {
        $plan = $this->plan->with([
            'reviewedBy',
            'createdBy',
            'contents'
        ])->findOrFail($plan_id);
        $plan->contents->map(function ($content) {
            $content->taskable;
            $content->taskable->domain;
            $content->taskable->subdomain;
            return $content;
        });
        return $plan;
    }

But i want to make like this

return $this->plan->with([
            'reviewedBy',
            'createdBy',
            'contents',
            'contents.taskable',
            'contents.taskable.domain',
            'contents.taskable.subdomain',
        ])->findOrFail($plan_id);

I would appreciate it if anyone help

question from:https://stackoverflow.com/questions/65858013/laravel6-eager-loading-with-dynamic-ownerkey-in-morphto-relation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...