Laravel 4 automatically create relationships in BaseModel - using “with”-array or scopes or what?

こ雲淡風輕ζ 提交于 2019-12-13 05:06:41

问题


I have successfully created a few relations in a Model. This is the user-model

<?php 
  class User extends BaseModel{ 
    protected $table = 'users';

    public function group(){
        return $this -> belongsTo('UserGroup');
    }

    ...
  } 
?>

and this is the UserGroup-model (UserGroup.php)

<?php class UserGroup extends BaseModel{ ... } ?>

Every user can be in one group (the database-column is called 'group_id' in the users-table). If I want to do eager loading on this relation, it works perfectly fine, also for other models.

The problem is that I have a few models that have a lot of foreign keys and I don't want to create all relations manually. I want a function in the BaseModel that creates all those relations automatically, like

public function group(){
    return $this->belongsTo('Group');
}

based on an array that I would provide in each model, looking like this

protected $foreignKeys = array(array('key' => 'group', 'model' => 'UserGroup'), ...);

I have read that there is an array called 'with' that you can use, but it did not work for me. Somewhere else I read I should work with query scopes but I have no idea how that could help me.

Thanks for reading and your support!

Best regards, Marcel


回答1:


Ardent provides something like you'd want to implement: https://github.com/laravelbook/ardent/blob/master/src/LaravelBook/Ardent/Ardent.php#L347-L350.

As per comments:

You might find Ardent-like solution better for your situation in the end. Having all the relations in an array presents more advantages to defining them as methods - you can search through those arrays if you need etc. So probably this is the way to go for you



来源:https://stackoverflow.com/questions/24585894/laravel-4-automatically-create-relationships-in-basemodel-using-with-array-o

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