Extra information table joined without eloquent model

非 Y 不嫁゛ 提交于 2019-12-12 02:11:34

问题


Say I have an database table called Item (with a name and a type). Now depending on the type, the item has extra information: e.g. if it is a ScoredItem it has a Score. So I created a database table ItemScore, which assigns a score to an item.

I then have an eloquent model: Item (with the name and the type), but how should I go about adding this Score property.

An obvious solution would be to create a model: ItemScore and set the correct relation (using hasMany and belongsTo). But because it would only contain a score, this seems a bit overkill.

So the question is: is it possible to somehow specify this relation so that I can request the Score of an item (if it has one) and also set it so that it is correctly saved in the database, without creating this model class?


回答1:


What you want can be done with Polymorphic Relations, but you will need to create models to provide the necessary information to Eloquent about the relations. As you said, suppose you have Item's than can have extra information such as Score or anything else, let's it can have a SubItem instead.

You will have to define those models as shown below:

class Item extends Eloquent
{
    public function extrainfo()
    {
        return $this->morphTo();
    }
}

class Score extends Eloquent
{
    public function items()
    {
        return $this->morphMany('Item', 'extrainfo');
    }
}

class SubItem extends Eloquent
{
    public function items()
    {
        return $this->morphMany('Item', 'extrainfo');
    }
}

Then you will have a database structure as follow:

items
    id             - integer
    name           - string
    extrainfo_id   - integer
    extrainfo_type - string

scores
    id    - integer
    score - decimal

sub_items
    id   - integer
    name - string

This will automagically do what you need. When you do:

$extrainfo = $item->extrainfo;

The extrainfo relation on the Item model will return either a Score or SubItem instance, depending on which type of model owns the photo. That type is defined on the database table.

Note: This is not overkill, you can see that as meta information provided to tell Eloquent how to treat your relations.



来源:https://stackoverflow.com/questions/18546933/extra-information-table-joined-without-eloquent-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!