How to update a “one to many” relation in Laravel? (can't find it in the docs)
Question
<?php
class User extends Eloquent {
public function tickets()
{
return $this->hasMany('Tickets')
}
}
class Tickets extends Eloquent {
public function User()
{
return $this->belongTo('User')
}
}
//and how to update a Ticket that belongs To User?
// and this dosen't work...Who can tell me the reason ,thanks !
$ticket = User::find(1)->tickets()->where('type','sometype')->get();
$ticket.update(array('status' => 0));
Solution
The update()
query is documented quite plainly in the official docs:
User::find(1)->tickets()->where('type','sometype')->update(array('status' => 0));
I suspect the issue you're having is that the get()` query is returning multiple records. In order for your query to work, you'll need to treat the returned value as a collection if records, then iterate and operate on each record individually.
$tickets = User::find(1)->tickets()->where('type','sometype')->get();
foreach ($tickets as $ticket) {
$ticket->update(array('status' => 0));
}
Note that the correct syntax for invoking an Eloquent method requires a preceding arrow ->
– not a dot (.
).
$record.update(array('foo' => 'bar')); # Incorrect
$record->update(array('foo' => 'bar')); # CORRECT!
UPDATE:
Model names should always be singular, not plural. Therefore, the Ticket
model should be defined as follows:
class Ticket extends Eloquent { // `Ticket`, not `Tickets`
public function User()
{
return $this->belongTo('User')
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow