我有两张桌子的帖子和照片。每个帖子有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'];
}
答案 0 :(得分:2)
发布模型:
<?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 :(得分:1)
您需要创建2个模型,其中一个用于Posts,一个用于Photos。
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
{
//
}
然后在Post模型上创建hasMany关系以链接到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
视图中的语法会稍有不同,但这使您对功能的工作原理有了一个很好的了解。
答案 2 :(得分:0)
好吧,首先您应该像这样更改Post模型:
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
有关关系的更多信息,您可能需要阅读docs。
我希望这会有所帮助!