我有一个有两个透视表的表单。其中一个工作很好,但我似乎不能使第二个工作,尽管他们是相当相似的。不起作用的是一个名为'photos'的图像表和名为'releases'的表单上载。我使用“photo_id”和一个“release_id”字段将数据透视表称为“photo_releases”。
数据库透视表
下面是发布模式
class Release extends Model { public function photos() { return $this->belongsToMany('App\Photo', 'photo_releases', 'release_id', 'photo_id'); } }
和照片模式
class Photo extends Model { public function releases() { return $this->belongsToMany('App\Release', 'photo_releases', 'photo_id', 'release_id'); } }
和ReleaseController
public function store(ReleasesCreateRequest $request) { $input = $request->all(); $user = Auth::user(); if ($file = $request->file('photo_01')) { $file_name = preg_replace("/[^a-zA-Z0-9.]/", "", $file->getClientOriginalName()); $name = time() . 'photo_01' . $file_name; $file->move('images', $name); $input['photo_01'] = $name; $photo = new Photo(); $photo->url = $input['photo_01']; $photo->save(); } $release = Release::create($request->except('release_id')); dd($request->except('release_id'), $request->get('photo_id', []), $request->get('artiste_id', [])); $release->photos()->attach($request->get('photo_id', [])); $release->artistes()->attach($request->get('artiste_id', [])); return redirect('/admin06000/releases'); }
此函数中使用了两个透视表。使用
“$release->artistes()->attach($request->get('artiste_id',[]));”
正在正常工作,但照片不是。url被记录在正确的数据库中,图像上传良好,但数据透视表没有更新。如果有人能帮上忙,它将会得到很大的支持。
如果需要更改“关系中的选择”,请尝试此操作
with('photos')
至
with(['photos'=>function($query){$query->where(....)->get();}])...
use Image;
use Illuminate\Support\Facades\Input;
...
public function store(ReleasesCreateRequest $request)
{
$input = $request->all();
$user = Auth::user();
if ($file = $request->file('photo_01'))
{
$image= Input::file('photo_01');
$name = time().'photo_01'.'.'.$image->getClientOriginalExtension();
$path=public_path('/YourPath/'.$name);
Image::make($image->getRealPath())->save($path);
$photo = new Photo();
$photo->url = '/YourPath/'.$name;
$photo->save();
}
$release = Release::create
([
'release_field'=>$amount,
'release_field2'=>$amount2,
....
]);
$release->with('photos')->with(artistes)->get();
}```