Laravel에서 "일대다" 관계를 업데이트하는 방법은 무엇입니까?(문서에서 찾을 수 없습니다)
문제
<?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));
해결책
그만큼 update()
쿼리는 매우 명확하게 문서화되어 있습니다. 공식 문서:
User::find(1)->tickets()->where('type','sometype')->update(array('status' => 0));
당신이 겪고 있는 문제는 다음과 같습니다. get()` 쿼리 돌아오고 있다 다수의 기록.쿼리가 작동하려면 반환된 값을 레코드의 컬렉션으로 처리한 다음 각 레코드를 개별적으로 반복하고 작동해야 합니다.
$tickets = User::find(1)->tickets()->where('type','sometype')->get();
foreach ($tickets as $ticket) {
$ticket->update(array('status' => 0));
}
Eloquent 메소드를 호출하기 위한 올바른 구문에는 선행 화살표가 필요합니다. ->
– ~ 아니다 점 (.
).
$record.update(array('foo' => 'bar')); # Incorrect
$record->update(array('foo' => 'bar')); # CORRECT!
업데이트:
모델 이름은 항상 단수형, ~ 아니다 복수형.그러므로, Ticket
모델은 다음과 같이 정의되어야 합니다:
class Ticket extends Eloquent { // `Ticket`, not `Tickets`
public function User()
{
return $this->belongTo('User')
}
}
제휴하지 않습니다 StackOverflow