[英]SQLSTATE[HY000]: General error: 1364 Field 'agent_id' doesn't have a default value
I am getting errors because of the foreign key field.由于外键字段,我收到错误。 I have two Models ( Agent, Post ).
我有两个模型(代理,邮政)。 I cannot get the user's primary key to be saved as a foreign key in the posts table.
我无法将用户的主键保存为帖子表中的外键。 I can insert the data manually, and it links with the parent table, but when the user inserts from the form in view, it gives me that error any help?
我可以手动插入数据,它与父表链接,但是当用户从视图中的表单插入时,它给了我这个错误任何帮助吗?
Agent代理人
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Agent extends Model
{
use HasFactory;
public function posts(){
return $this->hasMany(Post::class);
}
}
Post邮政
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
public function user(){
return $this->belongsTo(Agent::class);
}
}
And here is my method in the controller to save the data.这是我在控制器中保存数据的方法。
public function savepost(Request $request)
{
$post = new Post;
$post->title = $request->title;
$post->description = $request->description;
$post->type = $request->type;
$saved = $post->save();
if ($saved) {
return back()->with('success', 'New post has been added successfuly');
} else {
return back()->with('fail', 'Something went wrong , try again later');
}
}
in my think, Post
model should have agent_id
and when create new Post
, agent_id
is required with current user->id
.在我看来,
Post
模型应该有agent_id
并且在创建新Post
时,当前user->id
需要agent_id
。 so it seems to be added agent_id
in new Post
object.所以似乎在新的
Post
对象中添加了agent_id
。
...
use Auth;
...
public function savepost(Request $request){
$post = new Post ;
$post->title = $request->title ;
$post->description = $request->description ;
$post->type = $request->type;
$post->agent_id = Auth::user()->id;
$saved = $post->save();
if($saved){
return back()->with('success','New post has been added successfuly');
}else{
return back()->with('fail' , 'Something went wrong , try again later');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.