简体   繁体   中英

Laravel user_id in Many-To-Many relationships

Firstly sorry for my bad English.


I have three simple Models:

User

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

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

}

Ticket

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);
    }
}

So, For creating a new Ticket it needs to create a Ticket and a Reply.

I'm using below method in TicketController for creating new Ticket :

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

But it returns this error :

SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "user_id" violates not-null constraint ...

The Question Is :

Why Laravel doesn't recognize the owner of TicketReply ?!

I hope I've explained clear enough.

PS:

Be aware of $request data is like this :

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

我认为您无法在创建重播票证时设置用户ID,因为该模型只有一个foregin密钥,您可以像这样进行解决:

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

We think that the right solution is manually specify the user ID and ticket. Good luck!

Laravel can't know it. It just knows that one field among others is the user_id on the ticket but it doesn't know that you want to use it. Also it looks like the code with that relationship not the 100% correct design.

What you want is:

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

Then create the ticket like you do and

Create the ticketReply like:

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

There are other ways as well, ie

$fields = $request->all();
$fields->user_id = $request->user()->id;
$fields->ticket_id = $ticket->id;
$ticketReply = \App\TicketReply::create($fields);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM