Reputation: 24061
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 {
}
Upvotes: 1
Views: 171
Reputation: 33048
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;
Upvotes: 1