【问题标题】:Laravel4 one-to-one relationship is not loaded when in testing environmentLaravel4 一对一关系在测试环境中没有加载
【发布时间】:2013-10-18 16:12:49
【问题描述】:

我目前正面临这种奇怪的行为。

<?php
// Models
class User extends \Eloquent {
    protected $table = 'user';
    public $timestamps = FALSE;

    public function credit() {
        return $this->hasOne('Credit', 'uid');
    }
}
class Credit extends \Eloquent {
    protected $table = 'user_credit';
    public $timestamps = FALSE;

    public function user() {
        return $this->belongsTo('User', 'uid');
    }
}

// Service
function doThings() {
    // This is always working 
    $credit = Credit::where('uid', $user->id)->first(); 
    // This doesn't work in test environment, but it does outside of it, i.e. in a route
    // $credit = $user->credit; 
    if (empty($credit)) {
        $credit = new Credit();
        // Set some fields... then save.
        $credit->foo = 'bar';
    }   
    $user->credit()->save($credit);
}

// Test
Service::doThings(); // <--- works as expected the first time
Service::doThings(); // <--- fails, trying to save a new record instead of updating.

// In a test route
Route::get('/test', function() {
    $user = User::find(1);
    Service::doThings(); // <--- works as expected
    Service::doThings(); // <--- works as expected
    Service::doThings(); // <--- works as expected
    return 'test';
});

问题是当通过 $user->credit 访问信用模型时,在测试环境中,模型没有加载,并且无论数据库中是否存在项目都返回 NULL。它在显式加载时工作,使用信用::find()。

在测试环境之外,一切正常。

有什么提示吗?

【问题讨论】:

    标签: php laravel-4 eloquent


    【解决方案1】:

    在你的课堂上

    class User extends \Eloquent {
        protected $table = 'user';
        public $timestamps = FALSE;
    
        public function credit() {
            return $this->hasOne('User', 'uid');
        }
    }
    

    您应该使用(使用自定义键 uidUser &lt;-&gt; Credit 之间建立一对一的关系)

    class User extends \Eloquent {
        protected $table = 'user';
        public $timestamps = FALSE;
    
        public function credit() {
            return $this->hasOne('Credit', 'uid'); // <---
        }
    }
    

    所以,你可以像这样查询

    $credit = User::find(1)->credit;
    

    【讨论】:

    • @brazorf,很高兴它有帮助:-)
    • 我意识到我在这里粘贴代码时犯了一个错误。我的用户关系正确指向 Credit,尽管根据 ORM 文档我正在使用 $this->belongsTo() 。事情还没有工作:(
    • 哪种方式(方法调用)不起作用?在您的示例中,有两种方式相互关联。
    猜你喜欢
    • 2013-10-29
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多