Search code examples
laraveleloquentquery-builderlaravel-7laravel-query-builder

Laravel Eloquent Advance Querying


I have 5 different tables as projects, systems, attachments, tasks, users on Laravel I haven't assign a relationship for each table what I am trying to do is linking each table using ID.

enter image description here

$objFetch = Task::addSelect(
            [
                'project_id' => Project::select('title')->whereColumn('project_id', 'projects.id'),
                'tester_id' => User::select('name')->whereColumn('tester_id', 'users.id'),
                'system_id' => System::select('name')->whereColumn('system_id', 'systems.id'),
                'assigned_id' => User::select('name')->whereColumn('assigned_id', 'users.id'),
            ],
        )->paginate(20);

This return the expected output as

       {
            "id": 1,
            "document_auto_id": 101,
            "document_type": null,
            "document_name": "Tasks",
            "file_name": "Task_394_1622175671_195.png",
            "file_extention": "png",
            "file_size": "105383",
            "note": null,
            "created_at": "2021-05-28T04:21:11.000000Z",
            "updated_at": "2021-05-28T04:21:11.000000Z"
        },

Question is there any solutions to get the attachments for each tasks?

Laravel Eloquent answer is highly appreciated instead of Query building


Solution

  • DB tables are often related to one another. therefore we can use table ID to get the output. the error occurs because I have not defined it on the Model. THE PROBLEM WAS SOLVED AS I DO FOLLOWING STEPS

    MODEL

    class Task extends Model
    {
        use HasFactory;
    
        protected $fillable = [
            'title',
            'priority',
            'project_id',
            'system_id',
            'tester_id',
            'assigned_id',
            'description',
            'status',
        ];
    
        protected $casts = [
            'attachments' => 'array',
        ];
    
        public function Attachment()
        {
            return $this->hasMany(Attachment::class, 'document_auto_id');
        }
    
        public function Project()
        {
            return $this->hasOne(Project::class, 'id', 'project_id');
        }
    
        public function System()
        {
            return $this->hasOne(System::class, 'id', 'system_id');
        }
        public function assignedTo()
        {
            return $this->hasOne(User::class, 'id','assigned_id');
        }
    
        public function testerTo()
        {
            return $this->hasOne(User::class, 'id','tester_id');
        }
    }
    

    FETCHING DATA WITH RELEVANT TABLES

    $objFetch1 = Task::with(
                'testerTo',
                'assignedTo',
                'System',
                'Project',
                'Attachment'
            )->get();