php - 查询枢轴关系
问题描述
我想使用 Eloquent 查询数据透视模型关系。
我有我的用户模型:
class User extends Authenticatable
{
public function preferences(): BelongsToMany
{
return $this->belongsToMany(Preference::class, 'user_preference')
->using(UserNotificationPreference::class) //Custom Pivot model
->withPivot([enabled, channel_id]);
}
}
这是自定义枢轴模型:
class UserNotificationPreference extends Pivot
{
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'enabled' => 'boolean'
];
/**
* Channel relation.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function channel(): BelongsTo
{
return $this->belongsTo(Channel::class);
}
}
和偏好模型:
class Preference extends Model
{
// protected $connection = "apodis";
/**
* The users that belong to the preference.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users(): BelongsToMany
{
return $this->belongsToMany(Preference::class, 'user_channel_notification_preference')
->using(UserNotificationPreference::class) //custom pivot
->withPivot(['preference_id', 'user_id', 'enabled', 'channel_id']);
}
}
从用户模型中,我想在查询自定义数据透视表关系 (Channel::class) 后检索首选项,例如:
$user->preferences()
->wherePivot('enabled', true)
->whereHasPivot('channel', function(Builder $query) {
//doesn't exists
})->get()
有没有办法做到这一点?
解决方案
(产品模型 Laravel) public function products() { return $this->belongsToMany('App\Product'); } (Shop Model Laravel)public function shop(){ return $this->belongsToMany('App\Shop');} 你可以指定数据透视表的实际字段名 public function products(){ return $this->belongsToMany ('App\Product','products_shops', 'shops_id', 'products_id');}在我们的循环中获取这些值的可能性 foreach ($shop-products as $product){echo $product->pivot->price; }
推荐阅读
- python - LSTM Keras 功能 API 层输入形状错误
- apache-pulsar - 我们是否应该担心 Pulsar 主题中的捆绑包过多?
- ruby-on-rails - 将键值对从 ruby Hash 保存到数据库?
- android - 挂起kotlin协程异步子函数
- python - 如何使用 Pandas 系列和 numpy 数组进行矩阵乘法并始终返回一个系列?
- kubernetes - 当我尝试使用 kubectl 连接 GKE 集群时出现连接问题
- android - 为什么我的场景中的矢量图形对象在我的游戏的 android 版本中被放大但在 mac 版本中没有被放大?
- c++ - 所需的输出是 66.6,但我越来越乱(如下所示),如何解决这个问题?
- sql - 当 DBA_TAB_PRIVS 表中不存在用户名时,如何确定用户具有哪些权限?
- c# - 将 # 字符替换为空格和 # 字符