Laravel user_id在多对多关系中

时间:2017-03-16 11:10:40

标签: php laravel relationship laravel-5.4

首先抱歉我的英语不好。

我有三个简单的模型:

用户

class User extends Authenticatable
{
    protected $fillable = [
        'first_name', 'last_name'
    ];

    public function tickets()
    {
        return $this->hasMany(Ticket::class);
    }

}

票务

class Ticket extends Model
{
    protected $fillable = ['user_id', 'title'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function replies()
    {
        return $this->hasMany(TicketReply::class);
    }
}

TicketReply

class TicketReply extends Model
{

    protected $fillable = ['user_id', 'ticket_id', 'text'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function ticket()
    {
        return $this->belongsTo(Ticket::class);
    }
}

因此,要创建新的Ticket,需要创建Ticket和Reply。

我在TicketController中使用以下方法创建新的Ticket:

public function createNewTicket(Request $request)
{
    $ticket  = $request->user()->tickets()->create($request->all());
    $replies = $ticket->replies()->create($request->all()); // Error occurs in this line
}

但它会返回此错误:

  

SQLSTATE [23502]:非空违规:7错误:列中的空值   “user_id”违反了非空约束......

问题是:

为什么Laravel不承认TicketReply的所有者?!

我希望我已经解释清楚了。

P.S:

请注意$request数据是这样的:

array:2 [▼
  "title" => "My Ticket Title" // `title` field of Ticket Model
  "text" => "Ticket Text Goes Here" // `text` field of TicketReply Model
]

3 个答案:

答案 0 :(得分:0)

我认为您无法在创建重放票证时设置用户ID,因为模型只有一个外键,您可以这样解决:

$replies = $ticket->replies()->create($request->all() + ['user_id' => $request->user()->id]);

答案 1 :(得分:0)

我们认为正确的解决方案是手动指定用户ID和票证。 祝你好运!

答案 2 :(得分:0)

Laravel无法知晓。它只知道其中一个字段是票证上的user_id,但它不知道您想要使用它。此外,它与具有该关系的代码看起来不是100%正确的设计。

你想要的是:

    Warning messages:
      1: In structure(c(), class = c(class(x), class(y))) :
      Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
    Consider 'structure(list(), *)' instead.
    2: Computation failed in `stat_interpolate_tern()`:
      only 1-4 predictors are allowed 

然后像你一样创建票证

创建ticketReply,如:

user has many tickets
user has many ticketreplies
ticket belongs to user
ticket has many ticketreplies
ticketreply belongs to ticket
ticketreply has many users

还有其他方法,即

$fields = $request->all();
$fields['user_id'] = $request->user()->id;
$ticket->replies()->create($fields);