我希望有人能帮助我解决我已经有很长一段时间的问题,但直到现在我才发布它。
我正在处理的项目使用具有嵌套关系的模型。为了简化问题的上下文,让我们设想一个具有许多子模型关系的父母:hasMany和belongsTo。
我通常创建新实例并填充属性,然后使用setRelation()和associate()方法手工关联它们(因为我喜欢使用父-子和子-父方法检索关系)。但是,在我调用toArray() (以及遍历其关系的许多其他模型方法)之后,无限循环就会出现。
问题是:我是否做了正确的事情,给setRelation和associate打分模型关系?如果没有,我将如何检索$model->children()/$model->parent()关系?
I与PHPUnit 8.5.5和PHP7.4.4 (cli)一起使用LaravelFramework7.14.1
这里是一个单元测试:
<?php
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
use Illuminate\Database\Eloquent\Model;
class Team extends Model {
protected $fillable = ['name'];
public function players()
{
return $this->hasMany(Player::class);
}
}
class Player extends Model {
protected $fillable = ['name'];
public function team()
{
return $this->belongsTo(Team::class);
}
}
class CircularReferencesTest extends TestCase
{
public function testCircularReference(): void
{
// new instances
$team = app(Team::class)->fill(['name' => 'team name']);
$player = app(Player::class)->fill(['name' => 'player name']);
// set relations
$team->setRelation('players', collect([$player]));
$player->team()->associate($team);
dd($team->toArray(), $player->toArray()); // ERROR: Segmentation fault (core dumped).
// dd($team->push()); // push calls save() method recursively @see https://laravel.com/docs/7.x/eloquent-relationships#the-push-method
dd($team, $player);
}
}我打电话给: ./vendor/phpunit/phpunit/phpunit --stop-on-failure --colors=always ./tests/Unit/CircularReferencesTest.php
发布于 2020-06-06 16:38:19
根据这
不能在数据库中尚未表示的两个模型之间创建关系。
为了创建关系,至少必须预先保存其中一个模型。
这是你代码中的第一个问题。
第二:设置一方的关系是远远不够的。你为什么要在另一边建立关系?
我是说:
这两句话中的一句就足够了:
$team->setRelation('players', collect([$player]));
$player->team()->associate($team);我更喜欢用“联合”的方法更清楚..。
https://stackoverflow.com/questions/62232827
复制相似问题