雄辩的ORM - 模型关系

时间:2015-08-06 12:37:39

标签: php mysql orm eloquent octobercms

我是 OctoberCMS / Lavarel ORM 的新手,我很难实现模型关系。我有两个数据库表/模型,其中一个表示有关程序A, B, C的一般信息,另一个表示与这些程序相关的不同级别的一般信息。

目标:我想检索某个程序的信息X + 检索与其关联的程序级别的所有信息。

模型

模型1 - 表格架构

    Schema::create('pgs_programs', function($table)
    {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->char('prog_code', 10); // Unique ID/SKU
        $table->string("prog_slug" )->nullable();
        $table->string("prog_title")->nullable();
        $table->text("prog_intro_title")->nullable();
        $table->text("prog_intro")->nullable();
        $table->text("prog_top_img" )->nullable();
        $table->timestamps();
    });

模型2 - 表格架构

    Schema::create('pgs_program_levels', function($table)
{
    $table->engine = 'InnoDB';
    $table->increments('id');
    $table->char('prog_code', 10); // Related to Parent Program ID/SKU
    $table->string('level_title')->nullable();
    $table->enum('prog_level', array(4,5,6,7))->nullable();
    $table->text('prog_duration')->nullable();
    $table->text("prog_desc")->nullable();
    $table->text("prog_assesments" )->nullable();
    $table->timestamps();
});

组件

namespace PGS\Program\Components;
use Cms\Classes\ComponentBase;
use PGS\Program\Models\Program;  // Model 1
use PGS\Program\Models\ProgramLevels; // Model 2

  public function onRun(){

    $Programmes = Program::all();
    $X = $this->param('programme');
    $Y = $this->param('disciplines');
    $slug = $X."/".$Y ;
    $arr = array();

       foreach($Programmes as $k){
                $arr[]= $k['prog_slug'];
            }
      if(in_array($slug, $arr) ){
          // here query both models
          // this query gets General info from table1
          $progInfo = Program::where('prog_slug', '=', $slug)->first(); 
                } else {
                    return $this->controller->run('404');
                }
}

我想了解/使用array Relations所以我可以在一个查询中执行以下操作。我知道我可以做多个查询:

查询1:

 $progInfo = Program::where('prog_slug', '=', $slug)->first(); 

然后查询2:

 $progLvlsInfo = ProgramLevels::where('prog_code', '=', $progInfo['prog_code'])->get();
 // returns array of all program levels

我在SO的帖子中发表了同样的问题。我尝试在程序模型中添加$belongTo,反之亦然,但没有成功..

 public $belongsTo = [
        'program' =>       ['PGS\Program\Models\ProgramLevels',
            'foreignKey' => 'prog_code']
    ];

我应该坚持如上所述进行两次查询,还是使用Join语句或使用模型中提供的关系..

public $hasOne = [];
public $hasMany = [];
public $belongsTo = [];
public $belongsToMany = [];
public $morphTo = [];
public $morphOne = [];
public $morphMany = [];
public $attachOne = [];
public $attachMany = [];

非常感谢!

1 个答案:

答案 0 :(得分:0)

定义类UserAccount

定义类游戏

UserAccount可以有超过1个游戏。

//UserAccount 
function games() {
    return $this->hasMany('Games', 'user_id');
}

UserAccount::find(1)->games();

参考:

http://laravel.com/docs/5.0/eloquent#querying-relations