Skip to content

Commit

Permalink
fix pivot timestamp columns without parent
Browse files Browse the repository at this point in the history
- check to see if `pivotParent` exists before getting its timestamp columns.
- if there is no parent, fallback to the parent `Model` methods.
- add tests. 1 for when a parent exists, and 1 for when it doesn't
  • Loading branch information
browner12 committed Apr 17, 2018
1 parent aad3820 commit dbc03fa
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/Illuminate/Database/Eloquent/Relations/Pivot.php
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ public function hasTimestampAttributes()
*/
public function getCreatedAtColumn()
{
return $this->pivotParent->getCreatedAtColumn();
return ($this->pivotParent) ? $this->pivotParent->getCreatedAtColumn() : parent::getCreatedAtColumn();
}

/**
Expand All @@ -224,7 +224,7 @@ public function getCreatedAtColumn()
*/
public function getUpdatedAtColumn()
{
return $this->pivotParent->getUpdatedAtColumn();
return ($this->pivotParent) ? $this->pivotParent->getUpdatedAtColumn() : parent::getUpdatedAtColumn();
}

/**
Expand Down
28 changes: 28 additions & 0 deletions tests/Database/DatabaseEloquentPivotTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Mockery as m;
use PHPUnit\Framework\TestCase;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;

class DatabaseEloquentPivotTest extends TestCase
Expand Down Expand Up @@ -119,6 +120,29 @@ public function testPivotModelTableNameIsSingular()

$this->assertEquals('pivot', $pivot->getTable());
}

public function testPivotModelWithParentReturnsParentsTimestampColumns()
{
$parent = m::mock('Illuminate\Database\Eloquent\Model');
$parent->shouldReceive('getCreatedAtColumn')->andReturn('parent_created_at');
$parent->shouldReceive('getUpdatedAtColumn')->andReturn('parent_updated_at');

$pivotWithParent = new Pivot();
$pivotWithParent->pivotParent = $parent;

$this->assertEquals('parent_created_at', $pivotWithParent->getCreatedAtColumn());
$this->assertEquals('parent_updated_at', $pivotWithParent->getUpdatedAtColumn());
}

public function testPivotModelWithoutParentReturnsModelTimestampColumns()
{
$model = new DummyModel();

$pivotWithoutParent = new Pivot();

$this->assertEquals($model->getCreatedAtColumn(), $pivotWithoutParent->getCreatedAtColumn());
$this->assertEquals($model->getUpdatedAtColumn(), $pivotWithoutParent->getUpdatedAtColumn());
}
}

class DatabaseEloquentPivotTestDateStub extends \Illuminate\Database\Eloquent\Relations\Pivot
Expand Down Expand Up @@ -152,3 +176,7 @@ class DatabaseEloquentPivotTestJsonCastStub extends \Illuminate\Database\Eloquen
'foo' => 'json',
];
}

class DummyModel extends Model
{
}

0 comments on commit dbc03fa

Please sign in to comment.