gpt4 book ai didi

php - Laravel 5 : Having trouble updating related model values by using save/push methods, 他们就是不工作

转载 作者:行者123 更新时间:2023-11-29 19:18:39 26 4
gpt4 key购买 nike

我正在尝试更新相关模型的一些值,但在分配新值并使用 save()push() 后,这些值不会更新数据库。更重要的是,执行只是在这些方法处停止,我所能看到的只是一个空白页面。没有错误,什么也没有,它只是没有到达 return 语句。如果我使用 try-catch,它只会跳过 save()push()

这是产品模型(只是没有与我当前尝试执行的操作无关的字段和方法):

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
protected $table = "products";

public $timestamps = false;

public $fillable = [
...
];

public function userProduct()
{
return $this->belongsTo("\\App\\Models\\UserProduct", "id", "product_id");
}
}

包含我尝试更新的字段的 UserProduct 模型:

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class UserProduct extends Model
{

protected $primaryKey = null;
public $incrementing = false;
protected $table = "user_product";

public $fillable = [
...
"is_featured",
"is_hidden_from_latest"
...
];

public function product()
{
return $this->belongsTo("\\App\\Models\\Product", "product_id", "id");
}

public function pendingProduct()
{
return $this->belongsTo("\\App\\Models\\PendingProduct", "target_product_id", "target_product");
}

}

来自 Controller 的代码:

$replaced_product_sku = Input::get("replaced_sku");
$new_product_sku = Input::get("new_sku");

$products = Product::with([
"userProduct" => function($q) {
$q->orderBy("updated_at", "asc");
}
])->where("product_status", "live")->get();

if (!$found_replaced = $products->where("item_sku", $replaced_product_sku)->first()) {
return redirect("admin/content")
->with("danger", "Replaced product was not found.");
}

if (!$found_new = $products->where("item_sku", $new_product_sku)->first()) {
return redirect("admin/content")
->with("danger", "The new featured product was not found.");
}

$found_replaced->userProduct->is_featured = 0;
$found_replaced->userProduct->is_hidden_from_latest = 1;
$found_new->userProduct->is_featured = 1;
$found_new->userProduct->is_hidden_from_latest = 0;

$found_replaced->userProduct->save();
$found_new->userProduct->save();

return redirect("admin/content")
->with("...", "...");

尝试使用push()方法而不是save(),但唯一发生的事情是执行在$found_replaced->userProduct->save处停止(); 并显示空白页。还尝试过这样的事情:

$found_replaced->update([
"userProduct.is_featured" => 0,
"userProduct.is_hidden_from_latest" => 1
]);

$found_new->update([
"userProduct.is_featured" => 1,
"userProduct.is_hidden_from_latest" => 0
]);

但仍然没有成功。

最佳答案

首先你必须修复关系:

产品模型中:

public function userProduct()
{
return $this->hasOne("\\App\\Models\\UserProduct", "product_id", "id");
}

UserProduct模型中:

public function product()
{
return $this->belongsTo("\\App\\Models\\Product", "product_id", "id");
}

关于php - Laravel 5 : Having trouble updating related model values by using save/push methods, 他们就是不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42561411/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com