<?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));
如何更新Laravel中的“一对多”关系? (在文档中找不到)
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- douchuitang0331 2014-02-25 02:19关注
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') } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 Oracle触发器记录修改前后的字段值
- ¥100 为什么这个恒流源电路不能恒流?
- ¥15 有偿求跨组件数据流路径图
- ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
- ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
- ¥15 CSAPPattacklab
- ¥15 一直显示正在等待HID—ISP
- ¥15 Python turtle 画图
- ¥15 stm32开发clion时遇到的编译问题
- ¥15 lna设计 源简并电感型共源放大器