Question

I am trying to do a single query to get back an order and the card to charge, but getting an error.

Card model:

class Card extends Eloquent {
    protected $guarded = array();

    public static $rules = array();

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function orders()
    {
        return $this->hasMany('Order');
    }
}

Order model:

class Order extends Eloquent {
    protected $guarded = array();

    public static $rules = array();

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function card()
    {
        return $this->hasOne('Card');
    }

    public function address()
    {
        return $this->belongsTo('Address');
    }

    public function orderItems()
    {
        return $this->hasMany('OrderItem');
    }
}

What I am trying to get back:

$order = Order::with('card')->find($id);

This obviously doesn't work and I have tried several combos. I think the issue is with my models/relationships.

Any idea how I can get back the order with the card/token details?

DB info: Each order can have only one card_id and each card can be in many orders. There is no order_id in the card.

Orders table basically:

id | card_id

Cards table:

id | token

Trying to get the token col to return with the Order.

Was it helpful?

Solution

In your Order model, you need to change this:

public function card()
{
    return $this->hasOne('Card');
}

to this:

public function card()
{
    return $this->belongsTo('Card');
}

The reason is that you are defining the inverse of the hasMany relationship. With the belongsTo relationship, Eloquent will look for a card_id column on the orders table.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top