내 문제에 대한 답을 찾을 수 없으므로 올바르게 설명 할 수 있기를 바랍니다. 나는 필요한 모든 정보를 제공 할 수 있기를 희망합니다.Eloquent가 관계의 외래 키를 추가하지 않습니다.
하단 라인 : 부모 모델을 통해 새 데이터베이스 항목을 만들 때 관계 부모 ID가 삽입되지 않는 이유는 무엇입니까?
나는 그림 모음을 보유하고있는 경우 모델이 있습니다. addPicture ($name, $filepath)
메서드 내에서 예외가 throw됩니다.
Occasion.php
에게 코드 주석 rhough// namespace + use directives omitted
class Occasion extends Model
{
use Sluggable;
protected $fillable = [ 'name', 'root-folder', 'path' ];
public function sluggable()
{
return [
'slug' => [
'source' => [ 'root-folder', 'name', ],
],
];
}
public function pictures()
{
return $this->hasMany(picture::class);
}
public function addPicture ($name, $filepath)
{
$thumbname = $this->getThumbFilename($filepath);
dump($this,$this->pictures()); // dump to check my data
$pic = Picture::create(compact('name', 'thumbname'));
// this line is never reached
$pic->createThumb($filepath);
}
...
}
Picture.php을 지적 :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Spatie\Glide\GlideImage;
class Picture extends Model
{
protected $fillable = [ 'name', 'thumbname' ];
public function createThumb ($filepath)
{
$this->ppath = storage_path('app') . "/" . $filepath;
$this->tpath = storage_path('app/public/thumbs') . "/" . $this->getfilename($filepath);
GlideImage::create($this->ppath)->modify([ 'w' => 100, 'h' => 100, 'fit' => 'max' ])->save($this->tpath);
$this->save();
}
public function occasion()
{
return $this->belongsTo(Occasion::class);
}
/* public function slideshow()
{
return $this->belongsToMany(Slideshow::class);
}*/
private function getfilename ($path)
{
$tmp = array_slice(explode('/', $path), -3);
return str_replace(" ", "-", implode("-", $tmp));
}
}
dump($this->pictures());
의 결과는 관계를 보여주고 열 사용 :
HasMany {#206 ▼
#foreignKey: "pictures.occasion_id"
#localKey: "id"
#query: Builder {#205 ▶}
#parent: Occasion {#215 ▶}
#related: Picture {#210 ▶}
}
하지만 내 경우에 내게 말하는 오류 메시지가 나타납니다 ._id (pictu res 테이블)에 기본값이 없습니다. 작성된 쿼리를 보면 occasion_id가 실제로 누락되었습니다. 내가 알 수없는 것은 occasion 객체를 통해 새로운 그림 인스턴스를 생성 할 때 ID가 삽입되지 않는 이유입니다.
QueryException
SQLSTATE[HY000]: General error: 1364 Field 'occasion_id' doesn't have a default value (SQL: insert into `pictures` (`name`, `thumbname`, `updated_at`, `created_at`) values (IMG_0015.JPG, 2006-PVanlage-06-IMG_0015.JPG, 2017-09-12 19:34:07, 2017-09-12 19:34:07))
필요한 모든 정보가 제공되기를 바랍니다.
[laracasts] (https://laracasts.com/series/laravel-from-scratch-2017/episodes/16) 'addPicture' 메소드가 Occasion 모델에 있지만 여기에 제안 된 것을 목표로했습니다. 그림을 직접 만들었고 관계를 사용하지 않았다. : $ this-> pictures() -> create (compact ('name', 'thumbname')); 나는 실수를 찾기 위해 구글을 시도하기 전에 12 번이나 비디오를 보았고이 간단한 것을 놓쳤다. 도움을 주신 덕분에 ! – chilly