我的应用程序有3个相互关联的表:用户,订户,subscriber_tokens。
users:
id | name | username
56 | Ngoni | ngoni
subscribers:
id | user_id | client_id
1 | 30 | 2
16 | 56 | 2
subscriber_tokens:
id | token | user_id | client_id
1 | e7ij3l00J... | 56 | 2
我的关系定义如下:
User.php
模型
public function subscribers()
{
return $this->hasMany('App\Models\Subscriber', 'client_id', 'id');
}
SubscriberToken.php
模型
public function subscriber()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
Subscriber.php
模型
public function user()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
现在,我已经定义了一个函数,该函数应该像这样链接3个表:
public function subscriberTokens(){
$subscriber_ids = $this->subscribers()->pluck('id')->toArray();
return SubscriberToken::whereHas('subscriber', function ($query) use($subscriber_ids){
$query->whereIn('subscribers.id', $subscriber_ids);
})->get();
}
因此,当我执行该函数时,会发生以下错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'subscribers.id' in 'where clause' (SQL: select * from `subscriber_tokens` where exists (select * from `users` where `subscriber_tokens`.`user_id` = `users`.`id` and `subscribers`.`id` in (1, 16)))
任何帮助将不胜感激。谢谢。
答案 0 :(得分:0)
这应该有效:
public function subscriberTokens(){
$subscriber_ids = $this->subscribers()->pluck('id')->toArray();
return SubscriberToken::whereHas('subscriber', function ($query) use($subscriber_ids){
$query->whereIn('user_id', $subscriber_ids);
})->get();
}