doq70020 2016-06-05 06:09
浏览 16

基于laravel中外键的第二个自动增量字段

I have a Lesson Model like this :

class Lesson extends Model
{
        use SoftDeletes;

        public $primaryKey = 'lesson_id';

        public function contents ()
        {
              return $this->hasMany('App\Content', 'lesson_id', 'lesson_id');
        }
}

And a `Content Model like this :

class Content extends Model
    {
        public $primaryKey = 'content_id';
        public $timestamps = false;

        public $fillable = ['lesson_id', 'order'];

        public function lesson ()
        {
            return $this->belongsTo('App\Lesson', 'lesson_id', 'lesson_id');
        }
}

In Content Model, there is an order column that increases after each content insertion based on lesson_id field like this:

|------|---------|---------------|
|  id  |lesson_id |     order     |
|------|---------|---------------|
|  1   |    1    |       1       |
|  2   |    1    |       2       |
|  3   |    1    |       3       |
|  4   |    2    |       1       |
|  5   |    1    |       4       |
|  6   |    1    |       5       |
|  7   |    2    |       2       |
|  8   |    3    |       1       |
|  9   |    3    |       2       |
|------|---------|---------------|

For that I must run below codes before each insertion query to Calculate order column for a specific lesson_id:

$lesson_id = $request->get('lesson_id')

$lastOrder =
    Content::whereHas('lesson', function ($query) use ($lesson_id) {
        $query->where('lesson_id', $lesson_id);
    })->max('order');


    if (is_null($lastOrder)) {
        $lastOrder = 0;
    }

    $newContent =
        Content::create(
            [
                'lesson_id' => $lesson_id,
                'order'     => $lastOrder + 1
            ]
         );

I want a way in laravel that this operations done on insertion new Content instance automatically.

Does anyone have a solution to this problem?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 微信小程序协议怎么写
    • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
    • ¥20 怎么用dlib库的算法识别小麦病虫害
    • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
    • ¥15 java写代码遇到问题,求帮助
    • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看