您好我有User Model
這樣Laravel 5.2另存關係屬於關聯一對多
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'role_id',
'email',
'password',
'full_name',
'address',
'phone',
'family_name',
'family_address',
'family_phone',
'idcard',
'status',
'balance',
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts(){
return $this->hasMany(Post::class);
}
,我有Post Model
這樣
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'user_id',
'title',
'content',
];
public function user(){
return $this->belongsTo(User::class);
}
}
,並在我的Posts Controller
public function store(CreatePostRequest $request)
{
$user = Auth::user();
$post = Post::create([
'title' => $request->title,
'content' => $request->content,
]);
$post->user()->associate($user);
return redirect()->route('admin.posts.index')->with('success', 'Post berhasil disimpan.');
}
我得到這個錯誤
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`rentcar`.`posts`, CONSTRAINT `posts_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into `posts` (`title`, `content`, `updated_at`, `created_at`) values (Judul, <p>Isi</p>, 2016-10-20 11:10:31, 2016-10-20 11:10:31))
我的商店方法代碼有什麼問題?
如果我想保存文章並將其與當前登錄用戶相關聯,我的代碼應該如何顯示?