【发布时间】:2016-12-03 19:41:15
【问题描述】:
我正在尝试将 belongsTo 插入我的数据透视表。我有一个具有一对多关系的 cmets 和 documents 表,以及一个具有一对多关系的 cmets 和 users 表多对多的关系。数据透视表是 comment_user。
我可以插入 belongsTo 关系,但我遇到了一个问题,我需要将 cmets id 与用户 id(当前用户)一起插入。在下面查看我的关系。
数据库图
模型:
评论
class Comment extends Model
{
protected $tables = 'comments';
protected $fillable =
[
'comment',
'document_id',
];
public function users()
{
return $this->belongsToMany('App\Models\User', 'comment_user', 'comment_id', 'user_id');
}
public function documents()
{
return $this->belongsTo('App\Models\Document');
}
}
用户:
class User extends Model implements AuthenticatableContract
{
use Authenticatable;
protected $table = 'users';
protected $fillable = [
'first_name',
'last_name',
'middle_name',
'email',
'username',
'address',
'password',
'role_permission_id',
];
public function comments()
{
return $this->belongsToMany('App\Models\Comment', 'comment_user', 'user_id', 'comment_id');
}
}
控制器:
class CommentController extends Controller
{
public function postComments(Request $request, Document $id)
{
$this->validate($request,
[
'comment' => 'required',
]);
$commentObject = new Comment();
$user = Auth::user();
$commentObject->comment = $request->comment;
$id->comments()->save($commentObject);
$commentObject->users()->sync(['comment_id' => $commentObject, 'user_id' => $user->id],false);
return redirect()->back();
}
}
问题
我只想插入模型评论的id 以及当前用户。我试过了,但它说。
$commentObject->users()->sync(['user_id' => $user->id],false);
SQLSTATE[23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(
webdev.comment_user,CONSTRAINTcomment_user_sender_id_foreignFOREIGN KEY (sender_id) REFERENCESusers(id) ON DELETE CASCADE) (SQL: 插入comment_user(comment_id,user_id) 值(36, 11))
正如您在此处看到的,36 是 Comment 的当前 ID,11 是登录用户的当前 ID。任何帮助我怎样才能做到这一点?
【问题讨论】:
-
离题:用户评论在大多数情况下是 1:n 关系。所以可以直接在comment表中插入user_id,不需要单独的join表。
-
请在您的问题中添加您的表结构
create table ...,以便我们检查约束。 -
u-nik 所说的非常重要,而不是离题。
$user->comments()应该是hasMany()类型。一个用户有很多 cmets,并且一个评论属于一个用户。你应该这样做,它会变得更简单。
标签: php laravel model-view-controller laravel-5.2