Добавить новый элемент в коллекцию eloquent - PullRequest
1 голос
/ 07 июня 2019

У меня есть две таблицы сообщений и фотографий. Каждый пост имеет 5 фотографий. Я хочу перечислить в каждом сообщении одну фотографию (аватарку), первое изображение.

$published_post = Post::where('created_by',auth()->user()->id)
                        ->where('status','published')
                        ->get();

$photo = Photo::where('post',$published_post->id)->get();

Эти два дают мне две разные коллекции. Как я могу добавить первую фотографию определенного сообщения в его массив, чтобы в поле зрения я мог отображать, используя цикл foreach.

Вот как я хочу видеть:

@foreach($published_post as $item)
    {{ $item->title }}
    {{ $item->profile_photo }}
@endforeach

Я пытался положить и нажать, но, похоже, не работает. Не уверен, как именно мы добавляем новую пару ключ-значение к объекту.

Две мои модели:

Schema::create('posts', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('title');
    $table->timestamps();
});

Schema::create('photos', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('image');
    $table->integer('post');
    $table->timestamps();
});

class Post extends Model
{
    protected $table = 'posts';
}


class Photo extends Model
{
    protected $table = 'photos';
    protected $fillable = ['image', 'post'];
}

Ответы [ 3 ]

2 голосов
/ 07 июня 2019

Почтовая модель:

<?php

    namespace App;
    use Illuminate\Database\Eloquent\Model;


    class Post extends Model
    {
        /*This is used to specify the table which this model is associated with*/
        protected $table = 'posts';

        protected $fillable = [
          'title'
        ];
        public $timestamps = true;

        public function photos(){
            return $this->hasMany(Photos::class,'post');
            //post is the foreign key for posts table
        }
    }

Фото Модель:

<?php

    namespace App;
    use Illuminate\Database\Eloquent\Model;


    class Photo extends Model
    {
        /*This is used to specify the table which this model is associated with*/
        protected $table = 'photos';

        protected $fillable = [
          'image', 'post'
        ];
        public $timestamps = true;

    }

Вид:

@foreach($published_post as $item)
    {{ $item->title }}
    {{ $item->photos->first()->image }} // photos relation is invoked and fetched first image
@endforeach
1 голос
/ 07 июня 2019

Вам нужно создать 2 модели, одну для постов и одну для фотографий.

php artisan make:model Post
php artisan make:model Photo
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Posts extends Model
{
    //
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Photo extends Model
{
    //
}

Затем создайте отношение hasMany в модели Post для ссылки на модель Photo

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use App\Photo;

class Post extends Model
{
    public function photos()
    {
        return $this->hasMany(Photo::class);
    }
}

Тогда, на ваш взгляд, вы можете лениво загружать фотографии, когда захотите

@foreach($posts as $post)
    {{ $post->title }}
    {{ $post->photo[0]->name}}
@endforeach

Синтаксис в вашем представлении будет немного отличаться, но это даст вам хорошее представление о том, как должна работать эта функциональность.

0 голосов
/ 07 июня 2019

Хорошо, сначала вы должны изменить модель своего поста следующим образом:

class Post extends Model
{
    protected $table = 'posts';

    public function photos()
    {
        return $this->hasMany(Photo::class, 'post');
    }
}

А затем добавьте следующее к вашей фотомодели:

class Photo extends Model
{
    protected $table = 'photos';

    public function post()
    {
        return $this->belongsTo(Post::class, 'post');
    }
}

Таким образом, вы создали связь между вашими моделями, и теперь вы можете получить свои данные следующим образом:

$published_post = Post::where('created_by',auth()->user()->id)
                      ->where('status','published')
                      ->with('photos')
                      ->get();

И, на ваш взгляд, вы можете получить первое фото следующим образом:

@foreach($published_post as $item)
    {{ $item->title }}
    {{ $item->photos()->first()->name }}
@endforeach

Для получения дополнительной информации об отношениях вы можете прочитать документы .

Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...