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 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果