Laravel 3에 간단한 앱을 쓰고 있는데 Item과 PeculiarItem이라는 두 가지 모델이 있습니다.Laravel 3/Eloquent ORM : 다른 모델을 확장 한 모델
PeculiarItem은 추가 필드 (예 : "color", "price"등)를 추가하여 항목을 확장해야합니다.
아이디어는 공통 항목 (예 : "우선 순위"또는 "제목")에 대해 "핵심"클래스 항목을 유지할 수 있으며 각기 고유 한 필드 집합을 가진 다양한 종류의 항목에 대해 확장 할 수 있습니다.
class Item extends Eloquent
{
// Just a simple model with a couple relationship with other models, such as Page, Collection
public static $table = 'items';
public function page()
{
return $this->belongs_to('Page');
}
public function collection()
{
return $this->belongs_to('Collection');
}
}
// ...
class PeculiarItem extends Item
{
public static $table = 'peculiar_items';
// Ideally this PeculiarItem needn't redeclare the page_id and collection_id foreign key fields
// because it extends Item.
}
문제는 ORM 하드 유선 내 PeculiarItem 객체에 저장() 메서드를 호출 할 때입니다 방식에서 비롯됩니다.
// ...
class Item_Controller extends Base_Controller
{
/**
* @param $type the class name of the object we are creating
* @param $data the data for the new object
* @return mixed
*/
public function action_create($type = null, $data = null)
{
// ... filter, validate data, etc.
$entry = new $type($data);
$entry->save();
}
}
// ...
예 POST 요청 : 항목// peculiaritem을 만들
데이터 : 페이지 ID = 1, collection_id를 = 1, 제목 = '푸', ...이 실패
PeculiarItem이 없기 때문에 필드 page_id 또는 collection_id.
이 상황을 어떻게 피할 수 있습니까? 원칙적으로 나쁜 생각입니까?
Item을 확장하는 15 개의 다른 클래스가 있다고 가정 해보십시오. 그런 다음 Item_Controller 내에서 객체 생성을 처리하는 15 가지 방법을 만들어야합니까? –
그건 중요하지 않습니다. 뻔뻔 스럽다. 'Item :: find (123) -> peculiar_items() -> get()'- 부모 항목과 관련된 모든 고유 항목을 반환 할 수 있습니다. 이 관계는'Item' 모델의'peculiar_items() {return $ this-> has_many ('peculiar_items', 'parent_key_name'); }' –
내 질문을 읽은 후에 상황이 명확하지 않다는 것을 깨달은 것일 수 있으므로 다른 시도가 있습니다. 여러 종류의 항목을 추가 할 수 있지만 모델/테이블을 DRY 상태로 유지할 수있는 API를 만들려면 어떻게해야합니까? 모든 항목에 특정 공통 기능 (우선 순위, 제목 등)이 있지만 모든 항목 종류마다 고유 한 특정 기능 (색상/무게, 가능한 조합)이 있다고 상상해보십시오. 내 목표는 모든 데이터를 즉시 가져 와서 올바른 종류의 Item 클래스를 인스턴스화하는 "create/item"과 같은 단일 API 호출을 갖는 것입니다. –