duanpeng1532 2014-04-17 11:11
浏览 42
已采纳

Laravel 4 - 选择相关型号

I have following table

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();
});

In the jokes table category_id is a foreign key and it has a one-to-many relationship with jokes_categories

In the model I have the following:

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');
    }
}

In the controller I have the following:

$jokes = Joke::all();

But it does not pull through joke_categories.name (I was under the impression that the model definition will directly help to pull related models)

What could be the solution?

  • 写回答

2条回答 默认 最新

  • duanlun2827 2014-04-17 11:25
    关注

    Your query is just on the Joke table.

    You could eagerload the categories ie.

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

    See docs: http://laravel.com/docs/eloquent#eager-loading

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?