【问题标题】:how to extend the get() method in eloquent如何在 eloquent 中扩展 get() 方法
【发布时间】:2013-09-03 14:56:13
【问题描述】:

如何在 eloquent 类中扩展 get() 方法,添加一些在调用时执行连接的代码。

每当调用all()、find 或get() 方法时,添加该连接:

static::join('clientes', 'clientes.id', '=', 'faturas.cliente_id');

谢谢

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    你试过eager loading吗?你也可以在你的模型中设置protected $with = array('clients');

    您还可以通过扩展 Model 类重载 newQuery 方法。

    class BaseModel extends Model {
    
        public function newQuery($excludeDeleted = true)
        {
            $builder = parent::newQuery($excludeDeleted);
    
            $builder->join('clientes', 'clientes.id', '=', 'faturas.cliente_id');
    
            return $builder;
        }
    }
    

    【讨论】:

    • 太棒了!还有一个问题......我在我的雄辩模型中创建了一个属性,比如 protected $ table = 'products';受保护的 $ view = 'v_products';如果调用的方法是像 all()、find() 或 get() 一样的“选择”,我想使用视图,但是,如果方法 update() 或 insert() 使用表。谢谢
    • 您能否提供更多关于您的观点的信息?您可以对视图执行 SQL 更新吗?视图有什么作用?
    猜你喜欢
    • 1970-01-01
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    相关资源
    最近更新 更多