Laravel hasmany function returns nothing

Joyner

When i m using has many without select it returns all fields from userTrancastion table

Invoicemodule.php

$invoice = UserInvoiceDetail::with('transaction')
            ->select('Id','UserId','TotalPrice')
            ->where('UserId','=',$playerId)
            ->get();
            return $invoice;

UserInvoiceDetail.php

class UserInvoiceDetail extends Model
{
    protected $table = 'user_invoice_details';
    protected $primaryKey ='Id';
    public function transaction() 
    {
        return $this->hasMany(UserTransaction::class, 'InvoiceId');
    }
}

Output

"Invoices": 
[
        {
            "Id": 1,
            "UserId": 5,
            "TotalPrice": 110,
            "transaction": [
                {
                    "Id": 1,
                    "InvoiceId": 1,
                    "UserId": 5,
                    "ReferenceTransactionId": null,
                    "CategoryId": 1,
                    "ProductId": 140,
                    "Price": 5,
                    "Quantity": 5,
                    "CustomerId": 1,
                },
                {
                    "Id": 2,
                    "InvoiceId": 1,
                    "UserId": 5,
                    "ReferenceTransactionId": null,
                    "CategoryId": 2,
                    "ProductId": 3,
                    "Price": 15,
                    "Quantity": 3,
                    "CustomerId": 1,
                }
            ]
        }
]

But When i m using has many with select it returns nothing userTrancastion table

UserInvoiceDetail.php

class UserInvoiceDetail extends Model
{
    protected $table = 'user_invoice_details';
    protected $primaryKey ='Id';

    public function transaction() 
    {
        return $this->hasMany(UserTransaction::class, 'InvoiceId')->select('user_transactions.Id','user_transactions.ProductId');
    }

}

Output

"Invoices": [
    {
        "Id": 1,
        "UserId": 5,
        "TotalPrice": 110,
        "transaction": []
    },
    {
        "Id": 2,
        "UserId": 5,
        "TotalPrice": 110,
        "transaction": []
    }
]

why this is happening, I want to use join in transaction() function, so i need only selective fields. How can use select with hasmany()? Thank you in advance.

DsRaj

The relation need to the column that by which it related so add InvoiceId also, it doesn't need to add user_transactions

public function transaction() 
{
    return $this->hasMany(UserTransaction::class, 'InvoiceId')->select('Id','ProductId','InvoiceId');
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related