Недвижимость не существует в коллекции: BelongsTo Realtion пусто - PullRequest
0 голосов
/ 12 апреля 2020

У меня есть пользователи и продукты. Пользователи могут сохранять / помечать товары, чтобы позже увидеть их позже.

Ниже я опубликую вам все мои три модели. Я хочу получить доступ к продукту, который помечен пользователем. Итак, я называю $user->markedProducts->product, который определяется как belongsTo отношение. Однако я не могу получить доступ к свойству product, поскольку оно не содержится в коллекции, хотя я написал protected $with = ['product']; в модели MarkedProduct.

У меня вопрос, как я могу получить доступ к каждому объекту продукта через MarkedProduct модель для печати таких вещей, как имя, заголовок и т. Д. c. продукта?

Ошибка, которую я получаю:

Property [product] does not exist on this collection instance.

Модель пользователя:

class User extends Authenticatable
{
    public function products()
    {
        return $this->hasMany('App\Product');
    }

    public function markedProducts(){
        return $this->hasMany('App\MarkedProduct');
    }
}

Модель продукта:

class Product extends Model
{

    /**
     * The relationships that should always be loaded.
     *
     * @var array
     */
    protected $with = ['comments'];

    /**
     * Get the user that owns the product.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

Маркированная модель продукта:

class MarkedProduct extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'products_marks';

    /**
     * The relationships that should always be loaded.
     *
     * @var array
     */
    protected $with = ['product'];

    /**
     * Get the user that owns the comment.
     */
    public function user()
    {
        return $this->belongsTo('App\User', 'user_id');
    }

    /**
     * Get the product that owns the comment.
     */
    public function product()
    {
        return $this->belongsTo('App\Product', 'product_id');
    }
}

Миграция продукта:

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id')->index();
        $table->unsignedBigInteger('supplier_id')->index()->nullable();
        $table->unsignedBigInteger('dispatch_country_id')->index()->nullable();
        $table->unsignedBigInteger('product_type_id')->index();
        $table->unsignedBigInteger('post_status_id')->index()->default(4);
        $table->string('slug', 400)->index()->unique();
        $table->string('url', 1000)->nullable();
        $table->string('image_url', 1000)->nullable();
        $table->string('voucher')->nullable();
        $table->timestamp('start_date')->nullable();
        $table->timestamp('end_date')->nullable();
        $table->string('heading');
        $table->text('description');
        $table->integer('price')->nullable();
        $table->integer('old_price')->nullable();
        $table->integer('percentage')->nullable();
        $table->integer('price_off')->nullable();
        $table->boolean('free_shipment')->nullable();
        $table->timestamps();

        $table->foreign('user_id')
            ->references('id')
            ->on('users');

        $table->foreign('post_status_id')
            ->references('id')
            ->on('post_statuses');

        $table->foreign('supplier_id')
            ->references('id')
            ->on('suppliers')
            ->onDelete('set null');

        $table->foreign('dispatch_country_id')
            ->references('id')
            ->on('dispatch_countries')
            ->onDelete('set null');

        $table->foreign('product_type_id')
            ->references('id')
            ->on('product_types');
    });
}

Миграция пользователя:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name')->unique();
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->date('birthday')->nullable();
        $table->integer('follower')->default(0);
        $table->integer('points')->default(0);
        $table->timestamps();
    });
}

Маркировка миграции продукта:

public function up()
{
    Schema::create('products_marks', function (Blueprint $table) {
        $table->unsignedBigInteger('product_id')->index();
        $table->unsignedBigInteger('user_id')->index();
        $table->timestamps();

        $table->foreign('product_id')
            ->references('id')
            ->on('products')
            ->onDelete('cascade');

        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
    });
}

Ответы [ 2 ]

1 голос
/ 12 апреля 2020

Приятно читать, я могу вам помочь.

Объяснение

Как уже упоминалось @ baceto90, вам не нужна модель MarkedProducts, потому что у вас есть многие ко многим отношения.

  • "У пользователя есть много отмеченных продуктов"
  • "Продукт отмечен многими пользователями"

Итак, вы действительно хотите получить users products или products users, а не markedProducts products. products_marks - это просто объединяющая таблица, которая используется для поиска всех products или users в соответствии с запросом. Это не laravel конкретный c, для получения дополнительной информации Google что-то вроде MySQL joining table many to many.

Отношения «многие ко многим» в моделях laravel определяются путем написания метода, который возвращает результат метода belongsToMany. Чтобы определить имя таблицы присоединяемой таблицы отношений, Eloquent объединит два связанных имени модели в алфавитном порядке. Вы можете переопределить это, передав второй параметр в belongsToMany.

https://laravel.com/docs/7.x/eloquent-relationships#many-ко-многим

Решение

  1. Игнорировать MarkedProducts Model
  2. Обновление отношения отмеченных продуктов в пользовательской модели. Тип return $ this-> ownToMany ('App \ Product', 'products_marks'); ,
  3. Получите markedProducts вот так: User::with('markedProducts')

Надеюсь, теперь все ясно. Если нет, просто спросите.

1 голос
/ 12 апреля 2020

Вам не нужна модель для маркированных продуктов. Просто прочитайте отношение ко многим .

...