laravel一对多

这个是公司大神写的借鉴一下

 1  <?php
 2 
 3 namespace App\Models\Web;
 4 
 5 use Illuminate\Database\Eloquent\Model;
 6 use Illuminate\Database\Eloquent\SoftDeletes;
 7 
 8 class PolicePage extends Model
 9 {
10     use SoftDeletes;
11 
12     protected $table = "police_page";
13 
14     protected $fillable = [
15         'pagename', 'singleScore', 'moreScore', 'token', 'page_type','deleted_at'
16     ];
17 
18     public function hasManyExam()
19     {
20         return $this->hasMany(PoliceExam::class,'pageid','id');
21     }
22 }
PolicePage模型
 1 <?php
 2 
 3 namespace App\Models\Web;
 4 
 5 use Illuminate\Database\Eloquent\Model;
 6 use Illuminate\Database\Eloquent\SoftDeletes;
 7 
 8 class PoliceExam extends Model
 9 {
10     //使用软删除
11     use SoftDeletes;
12 
13 
14     protected $table = 'police_exam';
15     public $fillable = [
16         'title',    'type',     'option_a', 'option_b', 'option_c',
17         'option_d', 'option_e', 'option_f', 'option_g', 'option_h', 'answer', '
18         score',     'pageid',   'token','deleted_at'
19     ];
20     public $timestamps=false;
21 }
PoliceExam模型

控制器中的代码

public function show(Request $request)//试卷详情
    {
//        1.使用头部id然后去查询身体外键得到身体的全部信息(ps:返回的id是头部的id)
        $head = PolicePage::with('hasManyExam')->find($request->id);
        $data = $head->hasManyExam;
        if (!empty($head) && !empty($data)) {
           return view('users.know.editPaper',compact('data','head'));
        }
    }

 

posted @ 2020-03-19 16:41  以己为镜  阅读(476)  评论(0编辑  收藏  举报