Search code examples
laraveleloquent

Why empty [created_by][user_profile] subarray in array in userProfile relation?


In Laravel 11 app I have sql request :

    $orders = Order::query()
        ->getByStatus(OrderStatusEnum::INVOICE)
        ->getById(6) // For debugging
        ->select(['id',
            'created_by_id',
            'order_number',
            'price_summary',
            'items_quality',
            'info',
            'created_at',
        ])

        ->with([
            'createdBy:id,name,email',
            'createdBy.userProfile:phone,website,notes',
            'orderItems:id,order_id,product_id,qty,price,total_price',
            'orderItems.product:id,title',
        ])
        ->get();

As Order with id = 6 has created_by_id = 2 tracing sqls:

SELECT `phone`, `website`, `notes`
    FROM `user_profile`
    WHERE `user_profile`.`user_id` in (2)

This row is found from user_profile table, but I see empty [created_by][user_profile] subarray

In app/Models/User.php I have :

public function userProfile(): HasOne
{
    return $this->hasOne(UserProfile::class);
}

and in app/Models/UserProfile.php :

public function user(): HasOne
{
    return $this->hasOne(User::class);
}

table user_profile is made with migration :

public function up(): void
{
    Schema::create('user_profile', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id')->nullable()->references('id')->on('users')->onDelete('CASCADE');

I suppose I have to use HasOne method in both models as 1 user can have only 1 profile...

What is wrong ?


Solution

    1. Correct the Relationship in UserProfile.php

    Change:

    public function user(): HasOne
    {
        return $this->hasOne(User::class);
    }
    

    To:

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }
    
    1. Ensure user_id is Included in the with() Query

    Modify:

    'createdBy.userProfile:phone,website,notes',
    

    To:

    'createdBy.userProfile:user_id,phone,website,notes',