我正在尝试使用和测试模型之间的关系。我能够测试方向上的关系,但我无法在方向上测试它。Ardent
FactoryMuff
belongs_to
has_many
我正在测试的模型是住宅房地产租赁应用程序及其相应的租赁历史。一个非常简化的数据库模式:
+--------------+
| applications |
+--------------+
| id |
| name |
| birthday |
| income |
+--------------+
+----------------+
| history |
+----------------+
| id |
| application_id |
| address |
| rent |
+----------------+
这是我的历史模型:
class History extends Ardent
{
protected $table = 'history';
public static $factory = array(
'application_id' => 'factory|Application',
'address' => 'string',
'rent' => 'string',
);
public function application()
{
return $this->belongsTo('Application');
}
}
这是我确保历史对象属于租赁应用程序的测试:
class HistoryTest extends TestCase
{
public function testRelationWithApplication()
{
// create a test rental history object
$history = FactoryMuff::create('History');
// make sure the foreign key matches the primary key
$this->assertEquals($history->application_id, $history->application->id);
}
}
这工作得很好。但是,我不知道如何测试另一个方向的关系。在项目需求中,一个租赁应用程序必须至少有一个与之关联的租赁历史对象。这是我的应用模型:
class Application extends Ardent
{
public static $rules = array(
'name' => 'string',
'birthday' => 'call|makeDate',
'income' => 'string',
);
public function history()
{
return $this->hasMany('History');
}
public static function makeDate()
{
$faker = \Faker\Factory::create();
return $faker->date;
}
}
这就是我试图测试这种has_many
关系的方式:
class ApplicationTest extends TestCase
{
public function testRelationWithHistory()
{
// create a test rental application object
$application = FactoryMuff::create('Application');
// make sure the foreign key matches the primary key
$this->assertEquals($application->id, $application->history->application_id);
}
}
这会导致ErrorException: Undefined property: Illuminate\Database\Eloquent\Collection::$application_id
我运行单元测试。对于我,这说得通。我没有告诉任何地方FactoryMuff
至少创建一个相应的History
对象来与我的Application
对象一起使用。我也没有编写任何代码来强制要求一个Application
对象必须至少有一个History
对象。
问题
- 如何执行“一个
application
对象必须至少有一个history
对象”的规则? - 我如何测试
has_many
关系的方向?