Created
April 19, 2023 13:27
-
-
Save cosmastech/9f9e600c622b658d56301e8e7cd2e98a to your computer and use it in GitHub Desktop.
LazyLoadFailTest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Tests\Feature; | |
use Illuminate\Database\Eloquent\Model; | |
use Illuminate\Database\Eloquent\Relations\MorphTo; | |
use Illuminate\Database\LazyLoadingViolationException; | |
use Illuminate\Database\Schema\Blueprint; | |
use Schema; | |
use Tests\TestCase; | |
class LazyLoadFailTest extends TestCase | |
{ | |
public function setUp(): void | |
{ | |
parent::setUp(); | |
Schema::dropIfExists('carts'); | |
Schema::create('carts', function (Blueprint $table) { | |
$table->id(); | |
$table->nullableMorphs('item'); | |
$table->timestamps(); | |
}); | |
Schema::dropIfExists('items'); | |
Schema::create('items', function (Blueprint $table) { | |
$table->id(); | |
$table->string('name'); | |
$table->string('other_data')->nullable(); | |
$table->timestamps(); | |
}); | |
Model::preventLazyLoading(); | |
} | |
public function testMorphableWithConstraintLoadsBaseName() | |
{ | |
Item::truncate(); | |
Cart::truncate(); | |
$item1 = Item::create(['name' => 'item 1']); | |
$item2 = Item::create(['name' => 'item 2']); | |
Cart::create(['item_type' => $item1::class, 'item_id' => $item1->id]); | |
Cart::create(['item_type' => $item2::class, 'item_id' => $item2->id]); | |
$carts = Cart::query()->with(['simple_item'])->get(); | |
foreach($carts as $i => $cart) { | |
$this->assertEquals('item '.($i+1), $cart->item->name); | |
} | |
$carts = Cart::query()->get(); | |
$exceptionsThrown = 0; | |
foreach($carts as $cart) { | |
try { | |
$cart->item->name; | |
} catch (LazyLoadingViolationException $exception) { | |
$exceptionsThrown++; | |
} | |
} | |
$this->assertEquals(2, $exceptionsThrown); | |
} | |
} | |
class Cart extends Model | |
{ | |
protected $guarded = ['*']; | |
protected $fillable = [ | |
'item_id', | |
'item_type', | |
]; | |
public function item(): MorphTo | |
{ | |
return $this->morphTo(); | |
} | |
public function simple_item(): MorphTo | |
{ | |
return $this->morphTo('item')->constrain([ | |
Item::class => function ($query) { $query->select(['id', 'name']); }, | |
]); | |
} | |
} | |
class Item extends Model | |
{ | |
protected $guarded = ['*']; | |
protected $fillable = [ | |
'other_data', | |
'name', | |
]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment