【问题标题】:laravel - query with foreign keylaravel - 使用外键查询
【发布时间】:2017-08-06 14:09:33
【问题描述】:

欢迎!我在数据库注释和飞行员中有两个表格,我想显示属于飞行员的注释。我在笔记表中添加了外键,但是当我尝试创建新笔记时遇到了这样的问题:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`app`.`notes`, CONSTRAINT `notes_pilot_id_foreign` FOREIGN KEY (`pilot_id`) REFERENCES `pilots` (`id`))

笔记模型:

 class Note extends Model
    {
      protected $table = 'notes';
        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'data', 'zadanie', 'uwagi', 'pilot_id',
        ];

        public function pilot() {
          return $this->belongsTo(Pilot::class);
        }
    }

试点模型:

class Pilot extends Model
{
  protected $table = 'pilots';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'phone', 'email',
    ];

    public function note() {
      return $this->hasMany(Note::class);
    }
}

注意控制器存储方法:

public function store(Request $request)

{

    $this->validate($request, [

        'data' => 'required',

        'zadanie' => 'required',

        'uwagi' => 'required',

    ]);


    $note = new Note (array(
      'data' => $request->get('data'),
      'zadanie' => $request->get('zadanie'),
      'uwagi' => $request->get('uwagi'),

    ));
    $note->save();
    $note->pilot()->sync($request->get('pilots'));

    return redirect()->route('uwagi.index')

                    ->with('success','Uwagi dodane poprawnie');

}

【问题讨论】:

  • 您应该检查迁移或数据库表的外键。

标签: php mysql laravel


【解决方案1】:

试试这个 return $this->hasMany('App\Note'); 和 尝试这个 return $this->belongsTo('App\Pilot');

【讨论】:

    【解决方案2】:

    问题解决了。我只是没有在迁移中删除公共功能中的外键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      • 2015-12-05
      相关资源
      最近更新 更多