我有一个发送群组电子邮件的功能,但我需要访问特定群组的联系人列表。我试过EagerLoading和链接,但似乎无法让它工作。所以在sendCommunications()
函数中,这一行引起了我的问题:
$contacts = $message->group->contact()->select(array('email_address'));
我从命令行收到的错误消息是:
Call to undefined method Illuminate\\Database\\Eloquent\\Collection::contact()
这就是我到目前为止所做的:
控制器功能:
public static function sendCommunications()
{
$queued_messages = QueuedMessage::with(array('message' => function($query)
{
$query->where('distribution_date_time', '<=', DB::raw('NOW()'));
}))->get();
foreach ($queued_messages as $queued)
{
$message = $queued->message;
$contacts = $message->group->contact()->select(array('email_address'));
foreach ($contacts as $contact)
{
Message::send($message->email_title.'\n'.$message->email_body, $contact->email_address, $message->department->short_name);
}
$queued->delete();
}
}
模型:
QueuedMessage:
class QueuedMessage extends Eloquent
{
protected $primaryKey = 'queued_message_pk';
protected $table = 'queued_messages';
public $timestamps = false;
public function message()
{
return $this->belongsTo('Communication', 'message_fk');
}
}
通信:
class Communication extends Eloquent
{
protected $primaryKey = 'message_pk';
protected $table = 'messages';
public $timestamps = false;
public function establishment()
{
return $this->belongsTo('Establishment', 'establishment_fk');
}
public function group()
{
return $this->belongsToMany('Group', 'messages_groups', 'message_fk', 'group_fk');
}
}
组:
class Group extends Eloquent
{
protected $primaryKey = 'group_pk';
protected $table = 'groups';
public $timestamps = false;
public function department()
{
return $this->belongsTo('Department', 'department_fk');
}
public function contact()
{
return $this->belongsToMany('Contact', 'contacts_groups', 'group_fk', 'contact_fk');
}
public function message()
{
return $this->belongsToMany('Communication', 'messages_groups', 'group_fk', 'message_fk');
}
}
与
class Contact extends Eloquent
{
protected $primaryKey = 'contact_pk';
protected $table = 'contacts';
public $timestamps = false;
public function department()
{
return $this->belongsTo('Department', 'department_fk');
}
public function group()
{
return $this->belongsToMany('Group', 'contacts_groups', 'contact_fk', 'group_fk');
}
}
答案 0 :(得分:0)
这是由于group()
返回一个集合,即一组结果,而不是一个结果。
您无法对一组项目进行方法调用。
您可以循环浏览group
中返回的项目,然后依次致电contact
每个项目,ala
$contacts = array();
foreach($message->group as $group){
merge_array($contacts, $group->contact()->select(array('email_address')));
}
答案 1 :(得分:0)
如果您注意到您的Eloquent课程Communication
,则会使用belongsToMany
关系。当您致电$message->group
时,这将返回Collection
个小组。
你可以尝试
$message->group->each(function($group) use($message){
$group->contact()->get('email_address')->each(function($contact) use($message){
Message::send($message->email_title.'\n'.$message->email_body, $contact->email_address, $message->department->short_name);
});
});
Eloquent Collection提供了一个each函数来遍历集合,该集合将回调作为参数来执行集合的附加操作。 希望这有帮助