【问题标题】:Laravel 4 - Select related modelsLaravel 4 - 选择相关模型
【发布时间】:2014-06-01 15:09:49
【问题描述】:

我有下表

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(我的印象是模型定义会直接帮助拉取相关模型)

有什么解决办法?

【问题讨论】:

    标签: php orm laravel laravel-4 eloquent


    【解决方案1】:

    您的查询只是在笑话表上。

    您可以预先加载类别,即。

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

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

    【讨论】:

      【解决方案2】:

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

      public function jokesCategory()
      

      【讨论】:

        猜你喜欢
        • 2013-08-07
        • 1970-01-01
        • 1970-01-01
        • 2016-05-22
        • 2014-02-12
        • 2013-09-12
        • 1970-01-01
        • 2013-05-25
        • 1970-01-01
        相关资源
        最近更新 更多