1
votes

I'm following the information here:

http://laravel.com/docs/eloquent#one-to-many

I have an assets and sizes table.

An asset has many sizes.

So in my asset model I have:

class Asset extends Eloquent {

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

}

But when I do:

Asset::find(1)->sizes;

I get:

Class 'sizes' not found

Where am I going wrong?

Migrations are:

Schema::create('assets', function($table){
        $table->increments('id');
        $table->string('title');
    });

    Schema::create('sizes', function($table){
        $table->increments('id');
        $table->integer('asset_id')->unsigned();
        $table->foreign('asset_id')->references('id')->on('assets');
        $table->string('width');
    });

My classes are also namespaced:

In my controller:

<?php namespace BarkCorp\BarkApp\Lib;
use BarkCorp\BarkApp\Asset;

then later:

Asset::find(1)->sizes;

My models:

Asset:

<?php namespace BarkCorp\BarkApp;

use \Illuminate\Database\Eloquent\Model as Eloquent;

class Asset extends Eloquent {

public function sizes()
    {
        return $this->hasMany('BarkCorp\BarkApp\Size');
    }

}

Size:

<?php namespace BarkCorp\BarkApp;

use \Illuminate\Database\Eloquent\Model as Eloquent;

class Size extends Eloquent {

}
1
You need to create a class called sizes that extends Eloquent.Kemal Fadillah
Could you show an example , this isnt in the docs.panthro
How does your autoloading work? classmap or PSR-0/4? If you use PSR autoloading, you should ensure your folder and file names are absolutely exact - naming a class correctly but in an incorrect filename will cause a class not found error. Similarly, putting a class with a given namespace in a different namespace's directory does the same. It can be a bit of a nightmare. If you use classmap, make sure you do a composer dumpautoload to ensure it's picked up all your classes.alexrussell

1 Answers

1
votes

You need models for both and when you use a relationship function, it takes the class name as an argument, not the name of the table. The function name can be whatever you want so do whatever makes sense to you there.

class Size extends Eloquent {

    // This is optional for what you need now but nice to have in case you need it later
    public function asset()
    {
        return $this->belongsTo('Namespace\Asset');
    }
}

class Asset extends Eloquent {

    public function sizes()
    {
        return $this->hasMany('Namespace\Size');
    }
}

Namespace = the namespace you have on your Asset model.

$assetSizes = Namespace\Asset::find(1)->sizes;

or you can use use so you don't need to add the namespace each time you want to use Asset.

use Namespace;
$assetSizes = Asset::find(1)->sizes;

Or you can use dependency injection.

public function __construct(Namespace\Asset $asset)
{
    $this->asset = $asset;
}

$assetSize = $this->asset->find(1)->sizes;