vendredi 24 août 2018

Getting users of a page through the page roles, where the roles can be morphable

So, I have a pages model:

    Schema::create('pages', function (Blueprint $table) {
        $table->increments('id');
        $table->string('username');
        $table->string('name', 70);
        $table->text('about');
    });

I have a roles model:

    Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->morphs('owner');
        $table->integer('user_id');
        $table->integer('role')->default(1);
        $table->timestamps();
    });

And a user model:

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });

My roles table is a morphable table, meaning it can morph to many models that can have roles, so for this instance, the owner_type will be the Page model.

Now, in my pages model I am trying to get all the users associated with that page, like so:

/**
 * Get the users.
 *
 * @return \Illuminate\Database\Eloquent\Relations\HasManyThrough
 */
public function users(): hasManyThrough
{
    return $this->hasManyThrough(User::class, Role::class, 'user_id', 'id')
                ->where('owner_type', static::class);
}

Mock data:

User:

INSERT INTO `sumcv`.`users`(`id`, `name`, `username`, `email`, `password`, `gender`, `dob`, `relationship`, `about`, `tags`, `website`, `facebook`, `twitter`, `linkedin`, `verified`, `account_type`, `sns_acc_id`, `is_admin`, `is_active`, `stripe_id`, `card_brand`, `card_last_four`, `trial_ends_at`, `remember_token`, `created_at`, `updated_at`, `deleted_at`) VALUES (12, 'Schoen-Hegmann', 'sherman', 'jovan91@example.net', '$2y$10$Mxl9G1ypP.KyRnQ0rQ1X4ucROhHIOfuo25ANbAR/ySB8cxKoEFcI6', 'Unknown', NULL, NULL, 'Cross-platform multi-state standardization', NULL, NULL, NULL, NULL, NULL, 'verified', 'company', 'basic', 0, 0, NULL, NULL, NULL, NULL, 'rlFT1Q7rij', '2018-08-25 00:05:56', '2018-08-25 00:05:56', NULL);

Role:

INSERT INTO `sumcv`.`roles`(`id`, `owner_type`, `owner_id`, `user_id`, `role`, `created_at`, `updated_at`) VALUES (4, 'App\\Pages\\Entities\\Page', 1, 12, 1, '2018-08-25 00:07:32', '2018-08-25 00:07:32');

Page:

INSERT INTO `sumcv`.`pages`(`id`, `username`, `name`, `about`, `type`, `employees`, `phone`, `email`, `website`, `founded`, `accounts`, `created_at`, `updated_at`, `deleted_at`) VALUES (1, 'stewart45', 'Durgan Ltd', 'Veritatis sint aliquid fuga ut error omnis.', 'Publishing', '7A', NULL, NULL, NULL, NULL, NULL, '2018-08-25 00:05:59', '2018-08-25 00:05:59', NULL);

Now, when I do that, it returns an empty collection, even though there's data in there, what am I doing wrong?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2w8M0ec
via IFTTT

Aucun commentaire:

Enregistrer un commentaire