Laravel Eloquent 提前查询

Laravel Eloquent Advance Querying

我有 5 个不同的 table 作为 Laravel 上的 projects, systems, attachments, tasks, users 我没有为每个分配关系 table 我想做的是链接每个table 使用 ID。

$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);

这return 预期输出为

       {
            "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 高度赞赏答案而不是查询构建

DB tables 通常是相互关联的。因此我们可以使用 table ID 来获取输出。发生错误是因为我没有在模型上定义它。 我按照以下步骤解决了问题

型号

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');
    }
}

正在使用相关表获取数据

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