既雄辩模型之间的关系GalleryImage
和GalleryGroup
:是GalleryImage * <-> 1 GalleryGroup
。我要保存的实例GalleryGroup
,然后是GalleryImage
。
我想向您展示在您确实想做的情况下如何测试我的代码;-)。但是,我认为您实际上不需要测试。确实,代码非常简单。通过阅读它,如果您对Laravel的了解不止于我,也许您会发现问题并能够为我提供一些帮助。我让您阅读以下内容,但我想您会同意我的看法。
为GalleryGroup
和GalleryImage
(不属于主题)创建表。以下字段包含要创建的字段和表的名称。
复制/粘贴Eloquent模型和实例化它们的脚本,然后尝试将其保存在DB中。
创建您选择的路由来运行脚本,然后运行脚本(即:访问网页或使用REST客户端)
-GalleryGroup.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class GalleryGroup extends Model
{
use HasFactory;
protected $primaryKey = 'group_id';
private $name;
public function images() {
return $this->hasMany(GalleryImage::class);
}
}
-GalleryImage.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class GalleryImage extends Model
{
use HasFactory;
protected $primaryKey = 'image_id';
public function group() {
return $this->hasOne(GalleryGroup::class, 'group_id', 'image_id');
}
}
Eloquent模型GalleryGroup
被实例化并保存在db中;然后,GalleryImage
实例化Eloquent模型,应将其保存在db中:
$img_group = new GalleryGroup();
$img_group->name = 'foobar';
$img_group->save();
$image = new GalleryImage();
var_dump($img_group->group_id); // It exists and it's not empty
$image->group()->save($img_group);
$image->save();
最后一行永远不会执行,因为在以下行会引发此错误$image->group()->save($img_group);
:
Illuminate \ Database \ QueryException:SQLSTATE [23000]:违反完整性约束:1048文件/中的列'group_id'不能为null(SQL:update
gallery_groups
setgroup_id
=?,gallery_groups
。updated_at
= 2021-01-09 10:16:44其中group_id
= 24)第671行的var / www / html / api / vendor / laravel / framework / src / Illuminate / Database / Connection.php
我不明白为什么它试图更新组条目,我也不明白为什么group_id
是isNULL
或为空,因为$img_group
实际上有一个非空的group_id
(参见: line var_dump($img_group->group_id);
)。
实际结果是:1)GalleryGroup
正确实例化了模型并将其正确保存在db中; 2)GalleryImage
正确实例化了模型并且未将其保存在db中,因为出现了上述SQL错误。
预期的结果是:1)GalleryGroup
正确实例化模型并正确保存在db中; 2)GalleryImage
正确实例化模型并保存在db中。
我尝试var_dump
了几次变量,但是没有找到任何相关信息来帮助调试此问题。
我已经阅读并重新阅读了文档https://laravel.com/docs/8.x/eloquent-relationships#the-save-method和https://laravel.com/docs/8.x/eloquent#主键,但未找到任何相关信息来帮助调试此问题。
为什么会引发此错误,以及如何解决该错误?
这些关系之一必须为a,belongsTo
因为其中一个表具有与另一个表相关的外键。我假设GalleryImage属于GalleryGroup:
GalleryGroup
images
hasMany GalleryImage
GalleryImage
gallery
belongsTo GalleryGroup
一旦正确设置了这些,您就应该能够保存关系:
$img_group->images()->save($image);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句