这是我第一次将问题发布到stackoverflow,如果有任何遗漏,我很抱歉。
我现在正在使用laravel4.2
和xampp 1.8.3
。我有两个表如下:
表:任务 id int primary_key auto_incremental, 名称字符串.. 其他属性......
表:task_predecessors id int primary_key auto_incremental, task_id int外键引用任务.id task_predecessor_id int外键引用tasks.id
表任务在task_predecessors上没有任何FK引用,但是表task_predecessors有2个FK,它们都引用了表任务的同一主键。
这里的task_predecessors看起来像:
- id | task_id |predecessor_task_id
- 1 | 1 |11
- 2 | 1 |16
- 3 | 4 |3
情况: 一个任务可能(或可能不)充当其他任务的前任,并且给定任务可能(或可能不)具有前任任务。
我设计表格的原因: 我知道task_predecessors的PK没有意义,因为task_id和predecessor_task_id可以是复合PK。 为什么我创建了predecessor_tasks表,但不仅仅是将一个名为predecessor_task_id的列添加到表任务中:我不希望对同一任务有不同的pk值。
我的问题是:
我试过如下,我不知道它是否正确。
class Task extends \Eloquent {
public function taskpredecessor(){
return $this->belongsToMany('Task', 'task_predecessors', 'task_id', 'predecessor_task_id');
}
}
当我测试上面的代码时:return Task::find(1)->taskpredecessor;
结果如下:
**[*{"id":11,"name":"Task1","start_date":"2014-09-01 00: 00:00","end_date":"2014-09-06 00:00:00","duration":null,"progress":100,"theStatus":"completed","priority":"Norma l","predecessor_id":null,"approved":null,"file_id":null,"wbs_id":null,"created_at":"2015-02-12 05:10:45","updated_at":"2015-02-12 13:12:56","type":"Document","message_id":null,"notes":"Normal analysis","student_id":22,"optimistic":null,"most_likely":null,"pessimistic":null,"expected_time":null,"pivot":{"task_id":1,"predecessor_task_id":11}}*,***{"id":16,"name":"I dont know","start_date":"2014-09-01 00:00:00","end_date":"2014-09-23 00:00:00","duration":null,"progress":0,"theStatus":null,"priority":"Very Low","predecessor_id":null,"approved":null,"file_id":null,"wbs_id":null,"created_at":"2015-04-04 14:37:00","updated_at":"2015-04-05 02:13:40","type":"System","message_id":null,"notes":"","student_id":21,"optimistic":null,"most_likely":null,"pessimistic":null,"expected_time":null,"pivot":{"task_id":1,"predecessor_task_id":16}}***]**
正如你所看到的,我得到了两条记录,但它只显示了先行者信息,如何取回后继信息,即task_id:1及其详细信息。
非常感谢您的关注并在此阅读详细信息。