Проблема с отображением отношения пользователя к изображению в Laravel 5.8

Я очень новичок в Laravel.

У меня есть стандартная модель входа в систему (сгенерированная Laravel):

class UploadedFiles extends Model
{
    protected $quarded = [];
    protected $fillable = ['company_id', 'enable', 'photoable_type', 'photoable_id', 'path', 'ip', 'number'];
    protected $table = 'uploaded_files';


}


class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;
    use psCMS\Presenters\UserPresenter;

    public static $roles = [];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $fillable = ['company_id', 'enable', 'name', 'surname', 'email', 'email_verified_at', 'password', 'counter', 'url_address',  'isCompany', 'isMailing', 'content', 'nip1', 'business1', 'phone1', 'street1', 'number1', 'postal_code1', 'city1', 'country_id1', 'provincial_id1', 'nip2', 'business2', 'phone2', 'street2', 'number2', 'postal_code2', 'city2', 'country_id2', 'provincial_id2', 'nip3', 'business3', 'phone3', 'street3', 'number3', 'postal_code3', 'city3', 'country_id3', 'provincial_id3', 'cash', 'lng', 'lat', 'enable_map', 'remember_token', 'created_at', 'updated_at', 'last_login_at', 'last_login_ip' ];


    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];


    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }

    public function mainRole()
    {
        return $this->hasOne('App\Role');
    }

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


    public function images()
    {   // find(['photoable_type', '=', 'AdminImage'] ::with('director')->get();
        return $this->hasMany('App\UploadedFiles' );
    }

    public function images2()
    {   // ->where('photoable_type', 'AdminImage')
        return $this->hasManyThrough('App\UploadedFiles', 'App\User', 'photoable_id', 'id');
    }

    public function hasRole(array $roles)
    {

        foreach($roles as $role)
        {

            if (isset(self::$roles[$role]))
            {
                if (self::$roles[$role])  return true;

            }
            else
            {
                self::$roles[$role] = $this->roles()->where('name', $role)->exists();
                if (self::$roles[$role]) return true;
            }

        }
        return false;
    }

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

    public function companies()
    {
        return $this->belongsTo('App\Companies','company_id');
    }



}

Моя схема:

Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->boolean('enable')->default(0);
            $table->string('name', 120)->nullable();
            $table->string('surname', 120)->nullable();
            $table->string('email', 120)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->bigInteger('counter')->default(0);
            $table->string('url_address', 160);
            $table->boolean('isCompany')->default(0);
            $table->boolean('isMailing')->default(0);
            $table->text('content')->nullable();
            $table->string('nip1', 12)->nullable();
            $table->string('business1', 120)->nullable();
            $table->string('phone1', 60)->nullable();
            $table->string('street1', 150)->nullable();
            $table->string('number1', 8)->nullable();
            $table->string('postal_code1', 12)->nullable();
            $table->string('city1', 100)->nullable();
            $table->bigInteger('country_id1')->default(0);
            $table->bigInteger('provincial_id1')->default(0);
            $table->string('nip2', 12)->nullable();
            $table->string('business2', 120)->nullable();
            $table->string('phone2', 60)->nullable();
            $table->string('street2', 150)->nullable();
            $table->string('number2', 8)->nullable();
            $table->string('postal_code2', 12)->nullable();
            $table->string('city2', 100)->nullable();
            $table->bigInteger('country_id2')->default(0);
            $table->bigInteger('provincial_id2')->default(0);
            $table->string('nip3', 12)->nullable();
            $table->string('business3', 120)->nullable();
            $table->string('phone3', 60)->nullable();
            $table->string('street3', 150)->nullable();
            $table->string('number3', 8)->nullable();
            $table->string('postal_code3', 12)->nullable();
            $table->string('city3', 100)->nullable();
            $table->bigInteger('country_id3')->default(0);
            $table->bigInteger('provincial_id3')->default(0);
            $table->decimal('cash', 9, 2)->default(0);
            $table->decimal('lng', 10, 8)->default(0);
            $table->decimal('lat', 10, 8)->default(0);
            $table->boolean('enable_map')->default(0);
            $table->rememberToken();
            $table->timestamps();
            $table->engine = "InnoDB";
        });




Schema::create('role_user', function (Blueprint $table) {
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->bigInteger('role_id')->unsigned();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->engine = "InnoDB";
        });



Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->engine = "InnoDB";
        });



Schema::create('uploaded_files', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->boolean('enable')->default(0);
            $table->string('photoable_type', 150);
            $table->integer('photoable_id');
            $table->string('path', 255);
            $table->string('ip', 25);
            $table->bigInteger('number')->default(0);
            $table->timestamps();
            $table->engine = "InnoDB";
        });

У меня есть следующая запись в базе данных: https://ibb.co/ZhHGkKX

INSERT INTO `uploaded_files` (`id`, `company_id`, `enable`, `photoable_type`, `photoable_id`, `path`, `ip`, `number`, `created_at`, `updated_at`) VALUES
(46, 1, 1, 'AdminImage', 1, 'upload/images/AdminImage/627e653871183f639c8d9460f37111b1.jpg', '172.29.0.1', 0, '2019-05-27 08:50:08', '2019-05-27 08:50:08');
COMMIT;

В моей базе есть отношения: - uploaded_files.photoable_id = User.id

Мне нужно отобразить все изображения, принадлежащие пользователю, у которого есть photoable_type = AdminImage

Как я могу это сделать? Пожалуйста помоги

Стоит ли изучать PHP в 2023-2024 годах?
Стоит ли изучать PHP в 2023-2024 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Symfony Station Communiqué - 7 июля 2023 г
Symfony Station Communiqué - 7 июля 2023 г
Это коммюнике первоначально появилось на Symfony Station .
Оживление вашего приложения Laravel: Понимание режима обслуживания
Оживление вашего приложения Laravel: Понимание режима обслуживания
Здравствуйте, разработчики! В сегодняшней статье мы рассмотрим важный аспект управления приложениями, который часто упускается из виду в суете...
Установка и настройка Nginx и PHP на Ubuntu-сервере
Установка и настройка Nginx и PHP на Ubuntu-сервере
В этот раз я сделаю руководство по установке и настройке nginx и php на Ubuntu OS.
Коллекции в Laravel более простым способом
Коллекции в Laravel более простым способом
Привет, читатели, сегодня мы узнаем о коллекциях. В Laravel коллекции - это способ манипулировать массивами и играть с массивами данных. Благодаря...
Как установить PHP на Mac
Как установить PHP на Mac
PHP - это популярный язык программирования, который используется для разработки веб-приложений. Если вы используете Mac и хотите разрабатывать...
0
0
65
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

просто добавьте в модель пользователя

public function images2()
{   
    return $this->hasMany('App\UploadedFiles', 'company_id','company_id');
}

public function AdminImage()
{  
    return $this->images2()->where('photoable_type','=','AdminImage');
}

теперь вы можете получить доступ ко всем пользователям, у которых есть photoable_type = AdminImage

User::with('AdminImage')->get();

У меня ошибка: вызов неопределенного отношения [AdminImage] для модели [App\User].

trafficker 27.05.2019 16:41

извините, я пропустил полуклон в своем коде, попробуйте сейчас

Boni 27.05.2019 17:57

теперь у меня ошибка: SQLSTATE [42S22]: столбец не найден: 1054 Неизвестный столбец «users.photoable_id» в «списке полей» (SQL: выберите uploaded_files.*, users.photoable_id как laravel_through_key из uploaded_files внутреннего соединения users в users.id = uploaded_files.id где photoable_type = AdminImage и users.photoable_id в (1, 16)) :(

trafficker 27.05.2019 22:03

в нем четко сказано, что пользовательской таблицы photoable_id нет, вы ошиблись, я исправил, пожалуйста, посмотрите на это

Boni 28.05.2019 07:47

теперь вы не получаете никаких ошибок, я думаю, это потому, что вы делаете неправильное отношение, пожалуйста, узнайте о реализации laravel по этой ссылке laravel.com/docs/5.8/красноречивые отношения

Boni 28.05.2019 08:27

Вы объявили правильный метод в своей пользовательской модели, поэтому попробуйте изменить его:

 public function images()
{   
    // App\UploadedFiles must be a model
    return $this->hasMany(App\UploadedFiles::class, 'photoable_id', 'id');
}

Используйте отношение следующим образом:

User::with('images')->get();

С уважением

Другие вопросы по теме