【问题标题】:Laravel Pivot with multiple values具有多个值的 Laravel Pivot
【发布时间】:2016-04-22 17:49:33
【问题描述】:

我正在尝试使用 Laravel 构建一个(稍微复杂的)订阅服务。

订阅将属于以下类型: 早餐订阅,可在注册后 30 天内使用 20 份早餐。

例如,如果用户在 4 月 1 日注册早餐订阅,他可以选择任意 20 天使用,直到 4 月 30 日。

我已经制作了以下表格和相应的模型:

用户模型和表格

Users: 
- id
- name
- email
etc

订阅表和模型

Subscriptions: 
- id
- name
- price
- validity 
- meals_available

带有 softDeletes 的订阅用户数据透视表 (?)

- subscription_id
- user_id
- start_date
- end_date
- created_at
- updated_at
- deleted_at

我已经用 belongsToMany 关系更新了相应的模型

用户:

class User extends Authenticatable
{
     ...
    /*
     * User can have many subscriptions
     */

    public function subscriptions()
    {
        return $this->belongsToMany('App\Subscription')->withTimestamps();
    }
}

订阅模式

class Subscription extends Model
{
     ...
    /*
     * Subscription can have many Users
     */

    public function users()
    {
        return $this->belongsToMany('App\User')->withTimestamps();
    }
}

我需要帮助的问题 1. 数据库/模型结构是否正确解决问题?

  1. 虽然我可以使用 attach() 和 detach() 方法,但我无法在 subscription_table 中填写 start_date 和 end_date 值。这个怎么做?

  2. 我想在数据透视表上使用软删除。我该如何使用它?

提前致谢。

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    要从数据透视表中设置一个值,您可以使用:

    $user->subscriptions()->updateExistingPivot($subscriptionId, ['start_date' => '2016-01-01', 'end_date' => '2016-01-01']);
    

    $user->subscriptions()->attach([1 => ['start_date' => '2016-01-01', 'end_date' => '2016-01-01'], 2, 3]);
    

    要使用 softDelete,您可以使用这些方法中的任何一种来更新 deteled_at 并以这种方式检索约束关系的数据

    $this->belongsToMany('App\Subscription')->wherePivot('deleted_at','null');
    

    【讨论】:

    • 如何获取特定日期的特定记录?
    【解决方案2】:
    1. 还不确定。

    2. 附加方法与附加列。将模型设置为:

    public function subscriptions()
    {
    return $this->belongsToMany('App\Subscription')
    ->withTimestamps()
    ->whereNull('subscription_user.deleted_at')
    ->withPivot('start_date','end_date');
    }
    

    您可以将行更新为

    $user->subscriptions()->attach([1 => ['start_date' => '2016-04-01', 'end_date' => '2016-04-30'], 2, 3]);
    
    1. 您不能使用分离方法进行软删除。使用数据库查询进行更新。

    您可能希望添加类似这样的方法来检索给定用户的已删除行。

     public function subscriptionsWithTrashed()
        {
            return $this->belongsToMany('App\Subscription')->withTimestamps()->withPivot('start_date','end_date');
        }
    
        public function subscriptionsOnlyTrashed()
        {
            return $this->belongsToMany('App\Subscription')->whereNotNull('subscription_user.deleted_at')->withTimestamps()->withPivot('start_date','end_date');
        }
    

    【讨论】:

    • 是的,用户可以同时订阅早餐和午餐。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    相关资源
    最近更新 更多