【发布时间】:2014-12-18 07:49:45
【问题描述】:
基本上,我正在执行 ajax 调用,请求控制器将一定数量的“Artigo”(表示产品)添加到 Actividade(一种文档)。
它们是多对多的关系。
行为应该如下:
- 如果“Actividade”没有“Artigo”,则应附加它并在数据透视表中设置数量;
- 如果“Actividade”有它并且现有数量与传入数量相加为:
- 高于零,它只是简单地求和;
- 低于零,忽略它;
- 正好为零,将其分离;
- 在所有情况下,控制器都应返回附加到该“Actividade”的更新后的“Artigo”列表。
以下代码运行良好,但它会运行额外的查询以在返回 JSON 之前获取“Artigo”的更新列表。
// Controller
public function ajaxAddArtigo() {
if(Request::ajax()) {
try {
$actividade = Actividade::find(Input::get('actividadeId')); // Actividade is something like a "Document"
$artigo = Artigo::find(Input::get('artigoId')); // Artigo is a product
$actividade->addArtigo($artigo, intval(Input::get('qtd'))); // "qtd" is quantity
// if quantity of the Artigo becomes 0, the Artigo is detached and this doesn't return the updated collection (with the Artigo now detached)
// if the Artigo doesn't exist and quantity is a positive value, the Artigo gets attached, but this still doesn't return the updated collection (with the new Artigo attached)
return Response::json($actividade->artigos);
//return Response::json(Actividade::find(Input::get('actividadeId'))->artigos); // i must do this to return the updated list :(
} catch (Exception $ex) {
}
}
}
// Model Actividade
public function addArtigo(Artigo $artigo, $quantidade = 1) {
if($this->auth() || $this->authColab()) {
$actArtigo = $this->artigos->first(function($i, $item) use($artigo) { // get the wanted Artigo from the related Artigo's (or not, if it doesn't exist)
return $item->id == $artigo->id;
});
if(count($actArtigo)) { // if it exists
if($actArtigo->pivot->quantidade + $quantidade >= 0) { // we will see the effect of summing the quantity (it can be a negative number)
if($actArtigo->pivot->quantidade + $quantidade == 0) { // if it becomes 0, detach it
$this->artigos()->detach($artigo->id);
} else { // if it becomes bigger than 0, just sum it
$actArtigo->pivot->quantidade += $quantidade;
}
}
} else { // if it doesn't exist, add a new one as long as quantity is a cool value
if($quantidade > 0) {
return $this->artigos()->attach($artigo, [
'utilizador_id' => Auth::user()->id,
'quantidade' => $quantidade
]);
}
}
}
}
有没有办法告诉 Laravel 在执行 attach() 和 detach() 时也更新模型?
【问题讨论】: