【问题标题】:Trying to pull multiple rows from Database using a foreign key in Laravel尝试使用 Laravel 中的外键从数据库中提取多行
【发布时间】:2020-02-16 08:58:22
【问题描述】:

我正在尝试从数据库表 multi_image 中提取多个图像并显示它们,这些表具有链接到表 posts 中的一行的外键

posts 表中的每一行都链接到一个用户,但一个用户可以有许多帖子 1:M 关系

post的每一行可以有多张图片(最多4张)但是一张图片又只能属于一个帖子1:M

PostsController.php

<?php

namespace App\Http\Controllers;
use App\Multi_image;
use App\Post;

use App\User;
use DB;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use function Sodium\compare;

class PostsController extends Controller
{
public function __construct()
{
    $this->middleware('auth');
}

public function show(\App\Post $post)
{
    $postId = $post->id;
    $mImage = DB::table('multi_image')->where('post_id', $postId)->pluck('image');
    $postsIm = Post::whereIn('id', $mImage)->paginate(5);
    return view('posts.show', compact('post', 'mImage'));
}

Post.php

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $guarded = [];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function images()
    {
        return $this->hasMany(Multi_image::class);
    }
}

Multi_image.php

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Multi_image extends Model
{
    protected $table = "multi_image";

    public function post()
    {
        return $this->belongsTo('App\Post', 'post_id');
    }
}

show.blade.php

  @foreach($mImage as $image)
        <div class="details_image">
            <div class="details_image_thumbnails d-flex flex-row align-items-start justify-content-between">
                <div class="details_image_thumbnail" data-image=""><img src="{{ URL::to('/') }}/images/{{$image }}" alt=""></div>
            </div>
        </div>
        @endforeach
    </div>
    <div class="col-5">
        <img src="{{ URL::to('/') }}/images/{{$mImage->first() }}" class="w-100">
    </div>
                            .
                            .
                            .

帖子 posts table

多图像 multi_image table

解决方案

问题已用工作代码更正

使其工作的具体代码:查看 PostsController.php 中的 show()

【问题讨论】:

    标签: php laravel eloquent phpmyadmin


    【解决方案1】:

    它是未定义的,因为你没有在任何地方定义它。尝试在你的 foreach 中使用 App\Multi_image::all() as $image

    此外,您的模型类似乎有错误的名称。您应该称它们为 MultiImage 等 - 单数形式,以及 DB 中的复数表 - multi_images

    【讨论】:

    • 我已经设法使用另一种方法解决了这个问题并调整了代码谢谢你的建议,我会牢记在未来的实例中,我将对我的模型和数据库进行这些更改
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    相关资源
    最近更新 更多