[英]One to many relationship in eloquent
我在這里關注信息:
http://laravel.com/docs/eloquent#one-to-many
我有一個資產和尺寸表。
資產有多種尺寸。
因此,在我的資產模型中,我有:
class Asset extends Eloquent {
public function sizes()
{
return $this->hasMany('sizes');
}
}
但是當我這樣做時:
Asset::find(1)->sizes;
我得到:
Class 'sizes' not found
我要去哪里錯了?
遷移是:
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');
});
我的類也被命名為:
在我的控制器中:
<?php namespace BarkCorp\BarkApp\Lib;
use BarkCorp\BarkApp\Asset;
然后再:
Asset::find(1)->sizes;
我的模特:
資產:
<?php namespace BarkCorp\BarkApp;
use \Illuminate\Database\Eloquent\Model as Eloquent;
class Asset extends Eloquent {
public function sizes()
{
return $this->hasMany('BarkCorp\BarkApp\Size');
}
}
尺寸:
<?php namespace BarkCorp\BarkApp;
use \Illuminate\Database\Eloquent\Model as Eloquent;
class Size extends Eloquent {
}
兩者都需要模型,並且在使用關系函數時,它將類名作為參數而不是表名。 函數名稱可以是您想要的任何名稱,因此可以在那里進行任何有意義的操作。
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');
}
}
命名空間=您在Asset
模型上擁有的命名空間。
$assetSizes = Namespace\Asset::find(1)->sizes;
或者您可以使用use
這樣您就不必在每次要使用Asset
時都添加名稱空間。
use Namespace;
$assetSizes = Asset::find(1)->sizes;
或者,您可以使用依賴注入。
public function __construct(Namespace\Asset $asset)
{
$this->asset = $asset;
}
$assetSize = $this->asset->find(1)->sizes;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.