2014-09-04 2 views
0

Мне кажется, что я не получаю связи с бетоном в голове с Laravel. Попытавшись следовать документам для красноречивого орма, я все еще не могу получить свои внешние ключи от , например, (я обновляю их вручную). Сейчас я пытаюсь заставить систему доски объявлений работать. Пользователь может создать бюллетень пост, и вот он работает в моем контроллере:Комментарий/Почтовая система в Laravel

public function editPost($id) 
{ 
    $user = User::find($id); 
    $user->bulletin = new Bulletin;//new post 
    $user->bulletin->creator_id = $id;//why doesn't it automatically update given the relationship? 
    $user->bulletin->type = Input::get('type'); 
    $user->bulletin->title = Input::get('title'); 
    $user->bulletin->content = Input::get('bulletinEdit'); 
    $user->bulletin->save(); 

    if(Input::hasFile('bulletinImage')){ 
     $extension = Input::file('bulletinImage')->getClientOriginalExtension(); 
     $fileName = str_random(9).'.'.$extension; 

     $user->bulletin->photo = new Photo; 
     $user->bulletin->photo->user_id = $id; 
     $user->bulletin->photo->type = Input::get('type'); 
     $user->bulletin->photo->filename = $fileName; 
     $user->bulletin->photo->touch(); 
     $user->bulletin->photo->save(); 

     Input::file('bulletinImage')->move('public/images/bulletin/',$fileName); 
    } 

    return Redirect::to('bulletin'); 
} 

Если я отношения настроены должным образом, следует не creator_id обновляться автоматически? Вот что я имею в моей модели:

Бюллетень

<?php 

class Bulletin extends Eloquent { 

public function creator() 
{ 
    return $this->belongsTo('User'); 
} 

public function comments() 
{ 
    return $this->hasMany('Comment'); 
} 

public function type() 
{ 
    //if 1 then, etc 
} 

public function photos(){ 
    return $this->hasMany('Photo'); 
} 
} 

Пользователь

<?php 

use Illuminate\Auth\UserTrait; 
use Illuminate\Auth\UserInterface; 
use Illuminate\Auth\Reminders\RemindableTrait; 
use Illuminate\Auth\Reminders\RemindableInterface; 

class User extends Eloquent implements UserInterface, RemindableInterface { 

    use UserTrait, RemindableTrait; 

    /** 
    * The database table used by the model. 
    * 
    * @var string 
    */ 

    /** 
    * The attributes excluded from the model's JSON form. 
    * 
    * @var array 
    */ 
    protected $hidden = array('password', 'remember_token'); 

    public function tags() 
    { 
     //TO REMOVE RECORD 
     //User::find(1)->tags()->detach(); 

     return $this->belongsToMany('Tag'); 
    } 

    public function createUser() 
    { 
     $password = Hash::make('secret'); 
    } 

    public function bulletin() 
    { 
     return $this->hasMany('Bulletin','creator_id'); 
    } 

    public function profile() 
    { 
     return $this->hasOne('Profile'); 
    } 
} 

Может кто-нибудь дать мне несколько советов о том, затягивая это?

ответ

1

, как вы делаете это должно работать, вы просто используете больше кода и Красноречивым есть некоторые методы, чтобы помочь вам прикрепить отношения, поэтому я хотел бы попробовать что-то вроде этого:

public function editPost($id) 
{ 
    $user = User::find($id); 

    // Create a new bulletin, passing the necesssary data 

    $bulletin = new Bulletin(Input::only(['type', 'title', 'bulletinEdit'])); 

    // Attach the bulletin model to your user, Laravel should set the creator_id itself 

    $bulletin = $user->bulletin()->save($bulletin); 

    ... 

    return Redirect::to('bulletin'); 
} 

В вашей модели, вы 'll должны:

class User extends Eloquent implements UserInterface, RemindableInterface { 

    protected $fillable = ['type', 'title', 'bulletinEdit']; 

    ... 
} 

Таким образом, Laravel не дает вам исключение MassAssignmentException.

+0

Спасибо! Хорошо знать. Я получаю сообщение об ошибке с частью «нового бюллетеня», он возвращает исключение массового присваивания, которое просто говорит «тип», как его настроить, чтобы красноречивый отправил этот ввод в правильные столбцы? – aceslowman

+1

Извините, отредактировано, чтобы устранить эту ошибку. И я просто видел, что у вас есть другой столбец '$ user-> bulletin-> content = Input :: get ('bulletinEdit');', поэтому вы можете изменить его в своей форме или изменить массив, который вы передаете, на ' создать() '. –

Смежные вопросы