Laravel One To Many Сохранить вопрос - PullRequest
0 голосов
/ 04 ноября 2019

Нарушение ограничения целостности: 1048 Столбец 'restaurant_id' не может быть пустым (SQL: вставить в значения cover_photos (path, restaurant_id, updated_at, created_at) (smartmockups_k1gdx0ke_1572876856.jpg,,2019-11-04 14:14:16, 2019-11-04 14:14:16)) ОШИБКА

Я создаю новый ресторан с названием и местоположением. Теперь у него есть изображение обложки, которое я выбираю, однако при загрузке выдает эту ошибку.

отношение одно ко многим.

ФОТОГРАФИИ РЕСТОРАНА

public function coverPhoto()
    {
        return $this->hasOne('App\CoverPhoto');
    }

COVERPHOTO MODEL

public function restaurant()
    {
        return $this->belongsTo('App\Restaurant');
    }

Контроллер

    <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Restaurant;
use App\User;
use App\Photo;
use App\CoverPhoto;
class RestaurantController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $restaurants = Restaurant::findOrFail(1)->with('photos', 'coverPhoto')->get();
        //$restaurantCoverPhoto = Restaurant::findOrFail(1)->coverPhoto->get();

        return $restaurants;
        foreach($restaurants as $restaurant){
            echo $restaurant->coverPhoto->path;
        }



        return view('restaurants.restaurants')->with('restaurants', $restaurants);

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('restaurants.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
         $this->validate($request, [
            'name' => 'required',
            'location' => 'required',
            'cover_photo' => 'image|nullable|max:1999| mimes:jpeg,jpg,png'
        ]);
        // Handle File Upload
        if($request->hasFile('cover_photo')){

            // Get filename with the extension
            $filenameWithExt = $request->file('cover_photo')->getClientOriginalName();
            // Get just filename
            $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
            // Get just ext
            $extension = $request->file('cover_photo')->getClientOriginalExtension();
            // Filename to store
            $fileNameToStore= $filename.'_'.time().'.'.$extension;
            // Upload Image
            $path = $request->file('cover_photo')->storeAs('public/cover_photo', $fileNameToStore);
        } else {
            $fileNameToStore = 'noimage.jpg';
        }
        // Create Post
        $restaurant = new Restaurant;
        $coverPhoto = new CoverPhoto;

        $restaurant->name = $request->input('name');
        $restaurant->location = $request->input('location');

        $coverPhoto->path = $fileNameToStore;
        $coverPhoto->restaurant_id = 1;
        //return $coverPhoto;
        $restaurant->coverPhoto()->save($coverPhoto);

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

Я думаю, что происходит, так как это новый ресторан И новая фотография на обложке, для него требуется определить идентификатор для одногоили другой. Есть ли способ создать новый Ресторан и Coverphoto, который является отдельной БД?

Ответы [ 2 ]

0 голосов
/ 04 ноября 2019

Это очень просто, вы должны создать ресторан, а затем вы можете создать обложку ресторана

$restaurant = new Restaurant;
$coverPhoto = new CoverPhoto;

$restaurant->name = $request->input('name');
$restaurant->location = $request->input('location');
$restaurant->save();

$coverPhoto->path = $fileNameToStore;

$restaurant->coverPhoto()->save($coverPhoto);

Поскольку каждый раз, когда вы создаете или вставляете данные в ресторан, они создаются как объект, а затем после того, как вы можете создатьили вставьте данные в фотографию на обложке с отношениями один на один с рестораном

0 голосов
/ 04 ноября 2019

Просто сохраните сначала $restaurant:

$restaurant->save();
$restaurant->coverPhoto()->save($coverPhoto);

Таким образом, когда вы вставляете $coverPhoto через отношение, ваш $restaurant уже будет в БД и ему будет присвоен атрибут id.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...