我有兩張桌子posts,images我想用以下代碼獲取所有帖子和相關圖片:
$posts = Post::leftJoin('images','posts.postId','images.postId')
->where('countryId', $id)
->groupBy('posts.postId')
->orderby('posts.postId', 'desc')
->select('posts.*','images.*', 'posts.postId as postId')
->get();
但問題是我只得到一張帖子的圖片而不是所有圖片,因為一篇帖子有多張圖片。
當前的 Json 回應是:
[
{
"postId": 103,
"text": 'This is the post text',
"countryId": 75,
"imageId": 152,
"imageLink": "C9hGzwVKlOrL.jpg",
"imageDescription": ""
},
...
]
我想這樣改變它:
[
{
"postId": 103,
"text": 'This is the post text',
"countryId": 75,
"images" : [
{
"imageId": 152,
"imageLink": "C9hGzwVKlOrL.jpg",
"imageDescription": "This is the 1st image description"
},
{
"imageId": 153,
"imageLink": "JHKJdiuIuoi.jpg",
"imageDescription": "This is the 2nd image description"
},
...
]
},
...
]
uj5u.com熱心網友回復:
您不應該嘗試使用一個查詢來獲取分層/嵌套資料。Eloquent 具有“關系”功能:https : //laravel.com/docs/8.x/eloquent-relationships#one-to-many
在您的情況下,您需要向Post模型添加“影像”關系:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function images()
{
return $this->hasMany(Image::class, 'postId', 'postId');
}
}
然后:
$posts = Post::where('countryId', $id)
->orderBy('postId', 'desc')
->select('posts.*','images.*', 'posts.postId as postId')
->get();
foreach ($posts as $post) {
$post->images; // = collection of all images related to this post
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/420997.html
標籤:
