我已經創建了非常基本的模型。我有人桌子和電子郵件表。 我還在persons/show.blade.php
(「添加郵件」)中創建了一個鏈接。 我的模型是Laravel 4創建添加關係記錄表格
class Person extends Eloquent {
protected $table = 'persons';
public function email()
{
return $this->HasMany('Email');
}
}
和
class Email extends Eloquent {
protected $table = 'emails';
public static $rules = array(
'email'=>'required|unique:emails'
);
public function person()
{
return $this->belongsTo('Person');
}
}
我怎樣才能通過$person->id
到新的控制器?
在我show.blade.php
爲Person
我加
{{ HTML::linkRoute('email.adduseremail','Προσθήκη Email',array($person->id))}}
,我加入到我的EmailController
public function adduseremail($id)
{
return View::make('email.createforuser',['id'=>$id]);
}
public function storeforuser($pid)
{
$validator = Validator::make(Input::all(),Email::$rules);
if ($validator->fails()) {
$messages = $validator->messages();
foreach ($messages->all('<li>:message</li>') as $message)
return Redirect::back()->withInput()->WithErrors($messages);
}
$person = Person::FindorFail($pid);
$email = new Email;
$email->email = Input::get('email');
$email->person()->associate($person);
$email->save();
return Redirect::route('person.index');
}
和我createforuser
的看法是
<p>
{{Form::open(['route'=>'email.storeforuser'])}}
<div>
{{Form::label('email', 'Email:')}}
{{Form::input('text', 'email')}}
{{$errors->first('email')}}
</div>
</br>
<div>
{{Form::submit('Submit')}}
</div>
{{Form::close()}}
<p>
我不斷收到試圖獲取屬性非對象(查看:/var/www/laravel/app/views/email/show.blade.php
)
是否有任何使用窗體和模型插入新對象到數據庫'belongsTo'關係的例子?我找不到任何完整的東西,只是部分例子。
謝謝,我終於實現你的建議,因爲我的方式(見下文),我遇到問題時,驗證失敗,不得不重新定向到一個帖子路線 – geoandri 2014-09-29 06:33:19