繁体   English   中英

Laravel 4-选择相关模型

[英]Laravel 4 - Select related models

我有下表

Schema::create('jokes_categories', function(Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('is_active');
    $table->timestamps();
});

Schema::create('jokes', function(Blueprint $table) {
    $table->increments('id');
    $table->string('content', 200)->unique();;
    $table->enum('is_active', array('Y', 'N'));
    $table->integer('category_id')->unsigned();
    $table->foreign('category_id')->references('id')->on('jokes_categories');
    $table->timestamps();
});

在笑话表中category_id是一个外键,它与jokes_categories具有一对多关系

在模型中,我具有以下内容:

class Joke extends \Eloquent {

    public static $rules = array();

    // Don't forget to fill this array
    protected $fillable = array();

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

在控制器中,我有以下内容:

$jokes = Joke::all();

但这并没有joke_categories name (我的印象是模型定义将直接帮助提取相关模型)

有什么解决方案?

您的查询仅在笑话表上。

您可以渴望加载类别,即。

$jokes = Joke::with('JokesCategory')->get();

参见文档: http : //laravel.com/docs/eloquent#eager-loading

约定实际上是驼峰式而不是帕斯卡式,否则Laravel似乎不会自动加载关系。 我犯了同样的错误,无法弄清楚为什么我的关系无法自动加载。

public function jokesCategory()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM