Ad

Laravel - Chaining HasOne->belongsTo Relationship In Eloquent

- 1 answer

I have the following schema

CoinTransaction
    -id
    -name
    -paper_transaction_id
PaperTransaction
    -id
    -name
    -paper_product_id
PaperProduct
    -id
    -name

CoinTransaction and PaperTransaction has a 1 to 1 relationship through CoinTransaction.paper_transaction_id = PaperTransaction.id. PaperTransaction and PaperProduct has a many to one relationship through PaperTransaction.paper_product_id to PaperProduct.id.

I can connect CoinTransaction and PaperTransaction together in the CoinTransaction model using

    public function paperTransactions(){

        return $this->hasOne('PaperTransaction', 'id', 'paper_transaction_id');

    }

I've tried connecting all three together using

public function paperProducts(){

    $paperTransactions = $this->hasOne('PaperTransaction', 'id', 'paper_transaction_id');
    return $paperTransactions->getResults()->belongsTo('PaperProduct', 'paper_product_id');

}

But this returns no data related to PaperTransaction or PaperProduct.

Is there a way to chain the built-in Eloquent methods to get what I am looking for?

Ad

Answer

You can do it using a nested relationship, for example, in your CoinTransaction model use the following:

public function paperTransaction()
{
    return $this->hasOne('PaperTransaction', 'paper_transaction_id');
}

In your PaperTransaction model use the following:

public function paperProduct()
{
    return $this->belongsTo('PaperProduct', 'paper_product_id');
}

So now, you'll be able to query with relation using something like the following:

$coinTransaction = CoinTransaction::with('paperTransaction.paperProduct')->get();

So if you want to access the related model then you can do it like this way:

$paperTransaction = $coinTransaction->paperTransaction->toArray(); // or a field
$paperProduct = $coinTransaction->paperTransaction->paperProduct->toArray(); // or a field
Ad
source: stackoverflow.com
Ad