![](/img/trans.png)
[英]How to build Models for (possibly) polymorphic relationship with Laravel's Eloquent ORM
[英]Eloquent ORM - Models Relationship
我对OctoberCMS / Lavarel ORM相当陌生,并且我对实施模型关系有些犹豫 。 我有两个数据库表/模型,其中一个代表有关程序A, B, C
的常规信息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 = [];
非常感谢!
定义类UserAccount
定义班级游戏
一个UserAccount可以拥有多个游戏。
//UserAccount
function games() {
return $this->hasMany('Games', 'user_id');
}
UserAccount::find(1)->games();
参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.