belongsTo是怎么工作的?


我要做一个对数据进行评分的项目,每个project下面有一个数据表Data和一个评分表Score,每一条score都对应一个data,我想在调出一个score后通过belongsTo调用对应的data,请问如何让程序在执行return $this->belongsTo("App\ScoreCard\DataToScore");之前让data先执行setProject呢? 因为每一个project的data和score对应的数据表都不一样,具体到data,score模块中是通过setProject来指定对应表的。

大佬能不能告诉我如何实现,或者有其它更好的方案呢? 万分感谢!

以下为相关代码:

  //this a method in controller:
  public function show($id,Request $request)
    {
        $project = ScoreProject::findOrFail($request->get('project'));
        $score=new Score;
        return $score->setProject($project)->findOrFail($id)->data;
    }
  
  //below are the 2 models
  class DataToScore extends Model
{

    protected $project;

    public function setProject(ScoreProject $project)
    {
        $this->project = $project;
        $this->table = $project->data_to_score;
        $this->fillable(explode(",", $project->data_fillable));
        $this->project_id = $project->id;
        return $this;
    }

    public function score()
    {
        return $this->hasOne("App\ScoreCard\Score", "data_id");
    }

}
  
  
  class Score extends Model
{

    protected $project;

    public function setProject(ScoreProject $project)
    {
        $this->project = $project;
        $this->table = $project->score_save_to;
        $this->fillable(explode(",",$project->score_fillable));
        $this->project_id=$project->id;
        return $this;
    }
    public function setData($id){
        $this->data_id=$id;
        return $this;
    }
    
    public function data(){
        return $this->belongsTo("App\ScoreCard\DataToScore");
    }
}
  //project 对应模型,表名为score_projects
  class ScoreProject extends Model
{
    use \Illuminate\Database\Eloquent\SoftDeletes;
    protected $fillable=['name', 'description', 'data_to_score', 'score_save_to','audit_save_to','data_fillable','audit_fillable','score_fillable'];
    public function items(){
        return $this->hasMany('App\ScoreCard\ScoreItem','project_id')->orderBy('order');
    }
}

Vote Vote Cancel Collect Collect Cancel

<< 上一篇: 求助:Storage::makeDirectory () 无法创建目录问题

>> 下一篇: 学院页面出问题