我在两个模型(联系人和用户)上设置了一对一的关系。在意识到某些联系人没有与他们关联的用户后,我尝试编写一个播种器来捕获所有这些情况并创建用户模型并将其与联系人关联。但是,此脚本每次只能捕获大约一半的联系人。重复运行它最终会完成工作,但我想知道是什么原因造成的。
型号:
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()
方法。
看看Querying Relationship Absence 。
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();
并执行创建新用户并将其与联系人逻辑关联
关于php - Laravel 播种机偶尔会跳过记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56508912/