I’m having an issue with relations in two of my models in a Laravel application. My models are:

class Invoice extends Eloquent {

    protected $table = 'invoices';

    public function line_items()
    {
        return $this->hasMany('LineItem');
    }

}

And:

class LineItem extends Eloquent {

    protected $table = 'line_items';

    public function invoice()
    {
        return $this->belongsTo('Invoice');
    }

}

In my controller, I fetch an Invoice row with the following:

$invoice = Invoice::find($id);

However, if I try and access the line_items property to fetch the LineItem rows relating to my invoice, I get the following error:

Invalid argument supplied for foreach()

Why is this? I’ve set my models up as per Laravel’s documentation: http://laravel.com/docs/eloquent#one-to-many

有帮助吗?

解决方案

change

public function line_items() 

for

public function lineItems()

and it will work , tested in Laravel 4.1 :)

其他提示

Check your tables relations... (Schema)

Your FK must be lineitem_id... You have modified this? Laravel will configure automatically... Don't change this...

Then, try

$invoice->line_items() or $invoice->line_items in 4.1

Check for line_items before the foreach loop:

if(! $invoice->line_items->isEmpty()){
    foreach($invoice->line_items as $line_item){
        //do stuff
    }
}

Also, it won't hurt to explicitly mention the FK, although laravel will automatically try to do it for you provided you use proper names for your table fields.

//Invoice Model
return $this->hasMany('LineItem', 'invoice_id');

//LineItem Model
return $this->belongsTo('Invoice', 'invoice_id');
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top