【问题标题】:Show all data according to product_id in laravel-8根据 laravel-8 中的 product_id 显示所有数据
【发布时间】:2021-06-13 09:50:04
【问题描述】:

这是我的项目表。谁能帮我?我被困了2天

我可以在这里显示产品表的数据 您可以看到每个产品或应用程序都有唯一的 id 按钮,例如如果我单击 id 6,它将带我到下一页,我可以在项目表中上传一个 excel 文件。所以事情就像这个 App id:6 可以有很多项目数据,可以上传表单 excel 文件。并且excel文件的每个数据都有id

这是产品表 这是我可以创造产品的地方 如果我点击保存,然后我可以上传 excel 文件

这个 id 项目表

您可以在我的项目表中看到我可以根据product_id存储数据。在我的项目表中,我有三个product_id 1、2、3。我想根据product_id 显示它们。例如,如果我想显示 product_id 2 的数据,那么在我的 index.blade.php 中将只显示 product_id 2 的数据,而不是 product_id 1 和 3

这是我的index() projectController.php 方法

public function index()
    {
        $product = Product::with('projects')->where('user_id', Auth::id())->firstOrFail();
        $projects = $product->projects()->latest()->paginate(20);

        return view('projects.index', compact('projects'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }

这是我的 ProjectController.php 中的 show() 方法

public function show(Project $project)
    {
        return view('projects.show', compact('project'));
    }

这是用户模型 user.php

 public function Products(){
        return $this->hasMany('App\Models\Product');

    }

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

这是产品型号product.php

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'detail', 'image','color','logo','user_id'
    ];

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

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

这是项目模型project.php

class Project extends Model
{
    use HasFactory;

    protected $fillable = [
        'chapter_name',
        'sub_section_name',
        'title_1',
        'description_1',
        'image_1',
        'image_2',
        'image_3',
        'title_2',
        'description_2',
        'title_3',
        'description_3',
        'video_1',
        'video_2',
        'video_3',
        'user_id',
        'product_id'
    ];

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

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

这是 projectImport.php,我可以在其中上传 execl

class ProjectsImport implements ToModel, WithHeadingRow
{

    public function __construct()
    {
        Project::where('product_id',Product::where('user_id',Auth::id())->pluck('id')->last())->delete();
    }
    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function model(array $row)
    {
        return new Project([
            'chapter_name'     => $row['chapter_name'],
            'sub_section_name'    => $row['sub_section_name'],
            'title_1'    => $row['title_1'],
            'description_1'    => $row['description_1'],
            'image_1'    => $row['image_1'],
            'image_2'    => $row['image_2'],
            'image_3'    => $row['image_3'],
            'title_2'    => $row['title_2'],
            'description_2'    => $row['description_2'],
            'title_3'    => $row['title_3'],
            'description_3'    => $row['description_3'],
            'video_1'    => $row['video_1'],
            'video_2'    => $row['video_2'],
            'video_3'    => $row['video_3'],
            'user_id'    => auth()->user()->id,
            'product_id'    => Product::where('user_id',Auth::id())->pluck('id')->last()
        ]);
    }
}

这是我的 index.blade.php

@extends('layouts.app')

@section('content')

    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 8 CRUD </h2>
            </div>
            <div class="d-flex flex-row-reverse flex-column">
                <div class="d-flex">
                    <a class="btn btn-success text-light mr-5" data-toggle="medel" id="mediumButton" data-target="#mediumModel"
                    data-attr="{{ route ('projects.create')}}" title="upload project">
                        <i class="fas fa-cloud-upload-alt fa-2x"></i>
                    </a>
                    <form action="{{ route('importProject') }}" method="POST" enctype="multipart/form-data" class="d-flex">
                        @csrf
                        <input type='file' name="file">

                        <button class="btn btn-info" style="margin-left: -60px" title="Import Project">
                            <i class="fas fa-cloud-upload-alt fa-2x"></i></button>

                            <a class="btn btn-warning" href="{{ route('export') }}">Export User Data</a>
                    </form>

                </div>
            </div>
            <div class="pull-right">
                <a class="btn btn-success text-light" data-toggle="modal" id="mediumButton" data-target="#mediumModal"
                    data-attr="{{ route('projects.create') }}" title="Create a project"> <i class="fas fa-plus-circle"></i>
                </a>
            </div>
        </div>
    </div>

    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif

    <table class="table table-bordered table-responsive-lg table-hover">
        <thead class="thead-dark">
            <tr>
                <th scope="col">No</th>
                <th scope="col">Chapter Name</th>
                <th scope="col" >Sub-Section Name</th>
                <th scope="col">Title 1</th>
                <th scope="col">Description 1</th>
                <th scope="col">Image 1</th>
                <th scope="col">Image 2</th>
                <th scope="col">Image 3</th>
                <th scope="col">Title 2</th>
                <th scope="col">Description 2</th>
                <th scope="col">Title 3</th>
                <th scope="col">Description 3</th>
                <th scope="col">Video 1</th>
                <th scope="col">Video 2</th>
                <th scope="col">Video 3</th>

                <th scope="col">Date Created</th>
                <th scope="col">Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($projects as $project)
                <tr>
                    <td scope="row">{{ ++$i }}</td>
                    <td>{{ $project->chapter_name }}</td>
                    <td>{{ $project->sub_section_name }}</td>
                    <td>{{ $project->title_1 }}</td>
                    <td>{{ $project->description_1 }}</td>
                    <td>{{ $project->image_1 }}</td>
                    <td>{{ $project->image_2 }}</td>
                    <td>{{ $project->image_3 }}</td>
                    <td>{{ $project->title_2 }}</td>
                    <td>{{ $project->description_2 }}</td>
                    <td>{{ $project->title_3 }}</td>
                    <td>{{ $project->description_3 }}</td>
                    <td>{{ $project->video_1 }}</td>
                    <td>{{ $project->video_2 }}</td>
                    <td>{{ $project->video_3 }}</td>

                    <td>{{ date_format($project->created_at, 'jS M Y') }}</td>
                    <td>
                        <form action="{{ route('projects.destroy', $project->id) }}" method="POST">

                            <a data-toggle="modal" id="smallButton" data-target="#smallModal"
                                data-attr="{{ route('projects.show', $project->id) }}" title="show">
                                <i class="fas fa-eye text-success  fa-lg"></i>
                            </a>

                            <a class="text-secondary" data-toggle="modal" id="mediumButton" data-target="#mediumModal"
                                data-attr="{{ route('projects.edit', $project->id) }}">
                                <i class="fas fa-edit text-gray-300"></i>
                            </a>
                            @csrf
                            @method('DELETE')

                            <button type="submit" title="delete" style="border: none; background-color:transparent;">
                                <i class="fas fa-trash fa-lg text-danger"></i>
                            </button>
                        </form>
                    </td>
                </tr>
            @endforeach
        </tbody>
    </table>

    {!! $projects->links() !!}


    <!-- small modal -->
    <div class="modal fade" id="smallModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel"
        aria-hidden="true">
        <div class="modal-dialog modal-sm" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="smallBody">
                    <div>
                        <!-- the result to be displayed apply here -->
                    </div>
                </div>
            </div>
        </div>
    </div>


    <!-- medium modal -->
    <div class="modal fade" id="mediumModal" tabindex="-1" role="dialog" aria-labelledby="mediumModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="mediumBody">
                    <div>
                        <!-- the result to be displayed apply here -->
                    </div>
                </div>
            </div>
        </div>
    </div>


    <script>
        // display a modal (small modal)
        $(document).on('click', '#smallButton', function(event) {
            event.preventDefault();
            let href = $(this).attr('data-attr');
            $.ajax({
                url: href,
                beforeSend: function() {
                    $('#loader').show();
                },
                // return the result
                success: function(result) {
                    $('#smallModal').modal("show");
                    $('#smallBody').html(result).show();
                },
                complete: function() {
                    $('#loader').hide();
                },
                error: function(jq

【问题讨论】:

    标签: php laravel eloquent laravel-8


    【解决方案1】:

    您传递的是整个模型而不是 id

    public function index()
        {
            $product = Project::whereIn('product_id',Product::where('user_id',Auth::id())->pluck('id')->toArray())->firstOrFail();
            $projects = Project::where('product_id',$product->id)->latest()->paginate(20);
    
            return view('projects.index', compact('projects'))
                ->with('i', (request()->input('page', 1) - 1) * 5);
        }
    

    如果你使用relationships会更容易:

    class Project extends Model
    {
        public function product()
        {
            return $this->belongsTo('App\Models\Product');
        }
    }
    
    class Product extends Model
    {
        public function projects()
        {
            return $this->hasMany('App\Models\Project');
        }
    }
    

    然后像这样访问它:

    public function index()
        {
            $product = Product::with('projects')->where('user_id', Auth::id())->firstOrFail();
            $projects = $product->projects()->latest()->paginate(20);
    
            return view('projects.index', compact('projects'))
                ->with('i', (request()->input('page', 1) - 1) * 5);
        }
    

    更新:

    public function index()
        {
            $products = Product::with('projects')->where('user_id', Auth::id())->firstOrFail();
            $projects = $products->map(function($product) {
                return $product->projects()->latest()->first();
            })->flatten();
    
            return view('projects.index', compact('projects'))
                ->with('i', (request()->input('page', 1) - 1) * 5);
        }
    

    【讨论】:

    • 亲爱的兄弟 它不工作它只显示每个 id 的第一个 id 数据。它应该为每个 id 显示不同的数据。像 product_1 将显示 project_1 和 project_2。而 product_2 将只显示 project_3 和 project_3
    • 我添加了一个替代答案。您的查询看起来有点过于复杂。
    • 是的,在下一行 - 这就是我的预测。你真的要对关系进行分页吗?您可以执行以下操作,但我敢打赌,它不适用于分页:$projects = $products-&gt;map(function($product) { return $product-&gt;projects()-&gt;latest(); })-&gt;flatten();
    • 不客气。只需在latest() 之后添加-&gt;first()
    • 链接可能来自分页。我会删除它们。
    猜你喜欢
    • 1970-01-01
    • 2023-01-08
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多