I am working on Order-Ticket functionality. Many tickets should ideally be generated for a single order.
Earlier, the responsibility of creating tickets was written inside Order
Model and that time it worked fine but now that I am trying to move that responsibility to Ticket
model itself, it is not working.
I'll start with the Test file 'TicketTest.php'
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Concert;
use Carbon\Carbon;
use App\Order;
class TicketTest extends TestCase
{
use DatabaseMigrations;
/** @test */
function can_create_multiple_tickets_for_order(){
$numberOfTickets = 2;
// Arrange - Create Concert and Order
$concert = factory(Concert::class)->create(
[
'date' => Carbon::parse('December 1, 2016 8:00pm'),
]
);
$order = $concert->orders()->create([
'email' => 'abc@gmail.com'
]);
// Act - Create Tickets
$order->tickets()->createTickets($numberOfTickets); // This line throws call to undefined method.
// Assert
$this->assertEquals($numberOfTickets, $order->tickets()->count());
}
}
'Order.php' Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $guarded = [];
public function tickets()
{
return $this->hasMany(Ticket::class);
}
}
'Ticket.php' Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ticket extends Model
{
public function createTickets($ticketQuantity){
foreach(range(1, $ticketQuantity) as $i) {
$this->create([]);
}
}
public function order(){
return $this->belongsTo(Order::class);
}
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire