[英]Create one to many relation in FuelPHP
I have 3 models: Client, Task and Taskstatus(for matching tasks for each client). 我有3个模型:客户端,任务和任务状态(用于每个客户端的匹配任务)。
Model_Task 模型任务
protected static $_properties = array(
'id',
'name',
'created_at',
'updated_at',
);
Model_Client 型号客户
protected static $_properties = array(
'id',
'name',
'created_at',
'updated_at',
);
Model_Taskstatus Model_Taskstatus
protected static $_properties = array(
'id',
'client',
'task',
'created_at',
'updated_at',
);
I have added following to Model_Task 我已将以下内容添加到Model_Task
protected static $_has_many = array(
'taskstatuses' => array(
'key_from' => 'id',
'model_to' => 'Model_Taskstatus',
'key_to' => 'task',
'cascade_save' => true,
'cascade_delete' => false,
)
);
Model_Client 型号客户
protected static $_has_many = array(
'taskstatuses' => array(
'key_from' => 'id',
'model_to' => 'Model_Taskstatus',
'key_to' => 'client',
'cascade_save' => true,
'cascade_delete' => false,
)
);
Model_Taskstatus Model_Taskstatus
protected static $_belongs_to = array(
'client' => array(
'key_from' => 'client',
'model_to' => 'Model_Client',
'key_to' => 'id',
'cascade_save' => true,
'cascade_delete' => false,
),
'task' => array(
'key_from' => 'task',
'model_to' => 'Model_Task',
'key_to' => 'id',
'cascade_save' => true,
'cascade_delete' => false,
)
);
I want the taskstatus linked the client field to Client model, and task field to Task model, and if user insert a task with values which are not in Client or Task model (via id), an error should appear. 我希望taskstatus将客户端字段链接到客户端模型,将任务字段链接到任务模型,并且如果用户插入的任务的值不在客户端或任务模型中(通过id),则应该出现错误。 But it does not work (I can still add to clientstatus the value of client's id and task's id that doesn't exist in client and task tables.
但这是行不通的(我仍然可以在clientstatus中添加client和task表中不存在的client id和task id的值。
If you stick with the Model convention , the following will work just fine: 如果您坚持使用Model约定 ,那么下面的方法就可以了:
class Model_Task extends \Orm\Model
{
protected static $_belongs_to = array(
'client'
);
protected static $_properties = array(
'id',
'name',
'client_id',
'created_at',
'updated_at'
);
}
class Model_Client extends \Orm\Model
{
protected static $_has_many = array(
'task'
);
protected static $_properties = array(
'id',
'name',
'created_at',
'updated_at'
);
}
To get the tasks of a Client, you just have to do: 要获得客户的任务,您只需要做:
$client = Model_Client::find(1);
foreach($client->task as $task)
{
/* do something with each $task */
}
Edit: That way you avoid having an unnecessary table/model between Client/Task, forcing you to add valid tasks to existing clients. 编辑:这样可以避免在客户端/任务之间使用不必要的表/模型,从而迫使您将有效任务添加到现有客户端。 Besides, if you want a One to Many relationship between Client/Task, using a Model_Taskstatus would allow you to assign the same task to different clients, and that is not what you want.
此外,如果您希望客户端/任务之间存在一对多的关系,则使用Model_Taskstatus将允许您将同一任务分配给不同的客户端,而这不是您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.