Laravel 4在BaseModel中自动创建关系-使用"with"数组或范围或什么? [英] Laravel 4 automatically create relationships in BaseModel - using "with"-array or scopes or what?

查看:154
本文介绍了Laravel 4在BaseModel中自动创建关系-使用"with"数组或范围或什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功地在模型中创建了一些关系.这是用户模型

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');
    }

    ...
  } 
?>

这是UserGroup模型(UserGroup.php)

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

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

每个用户都可以在一个组中(数据库表在users-table中称为"group_id").如果我希望对此关系进行紧急加载,那么它对于其他模型也可以很好地工作.

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.

问题是,我有一些具有很多外键的模型,并且我不想手动创建所有关系.我想要BaseModel中的一个函数来自动创建所有这些关系,例如

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'), ...);

我已经读到可以使用一个名为"with"的数组,但是它对我不起作用.我在其他地方读过,我应该使用查询范围,但是我不知道这对我有什么帮助.

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.

感谢您的阅读和支持!

最好的问候,马塞尔

推荐答案

Ardent提供了您想要实现的功能:

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

根据评论:

最后,您可能会发现类似Ardent的解决方案更好地适合您的情况.将所有关系都放在一个数组中会为将它们定义为方法提供更多的优势-如果需要,您可以在这些数组中进行搜索.所以这也许是适合您的方法

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

这篇关于Laravel 4在BaseModel中自动创建关系-使用"with"数组或范围或什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆