繁体   English   中英

Laravel播种机偶尔会跳过记录

[英]Laravel seeder is skipping records sporadically

我在两个模型(联系人和用户)上建立了一对一的关系。 在意识到某些联系人没有与之关联的用户之后,我正在尝试编写一个播种器来捕获所有这些情况并创建用户模型并将其与联系人关联。 但是,此脚本每次只捕获大约一半的联系人。 反复运行最终会完成工作,但我想知道是什么导致了这一点。

楷模:

use Cartalyst\Sentry\Users\Eloquent\User as SentryUserModel;
class User extends SentryUserModel {
    public function contact()
    {
    return $this->hasOne('Contact');
    }
}
class Contact extends AppModel {
    protected $table = 'contacts';
    public function user()
    {
        return $this->belongsTo('User');
    }
}

这是播种机:

public function run()
{
    $contacts = Contact::all();


    foreach($contacts as $contact)
    {
        $user = $contact->user;

        if(!$user))
        {
            //Logic for creating and associating new user with contact
            //This is only being hit for about half of the contacts without a user_id in the db.
            Log::info('Found a contact without a user.');
        }
    }
}

我们希望这个播种机能够在没有用户的情况下捕获所有联系人,然后执行创建用户逻辑,但是它会捕获大约一半没有用户的联系人,并正确创建并关联新用户。 任何有关为什么会发生这种情况的见解将不胜感激。 提前致谢!

您可以使用doesntHave()方法。 看看查询关系缺席

public function run()
{
    $total_contacts = Contact::count();
    $total_contacts_with_user = Contact::has('user')->count();
    $total_contacts_without_user = Contact::doesntHave('user')->count();

    Log::info('Total contacts: ' . $total_contacts);
    Log::info('Total contacts with user: ' . $total_contacts_with_user);
    Log::info('Total contacts without user: ' . $total_contacts_without_user);

    Log::info('Check if this is true: ' . $total_contacts_with_user . ' + ' . $total_contacts_without_user . ' = ' . $total_contacts);
}

如果一切正常,并且您有所期望的所有联系人,请以这种方式获取没有用户的联系人:

$contacts_without_user = Contact::doesntHave('user')->get();

并执行创建和将新用户与联系逻辑相关联

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM