在Laravel Voyager相关表中搜索

发布于 2025-01-29 23:18:50 字数 1285 浏览 2 评论 0原文

有2个用于管理父母的类别的表,另一个用于子类别。当我想使用此关联的字段搜索时,我不能。并获取此错误

错误描述

  1. Hizmetler模型( sub-category ) :
    class Hizmetler extends Model
    {
        protected $primaryKey = 'hizmet_id';
        protected $table = 'hizmetler';
        public $incrementing = false;
    
        use SoftDeletes;
        protected $dates = ['deleted_at'];
        public function Hizmetler(){
            return $this->belongsTo(Hizmetler::class,'hizmet_ust_kategori');
        }
    }
  1. ustkategori模型( parent类别):
    class UstKategori extends Model
    {
        protected $primaryKey = 'id';
        protected $table = 'ust_kategori';
        public $incrementing = false;
    
        use SoftDeletes;
        protected $dates = ['deleted_at'];
        public function UstKategori(){
            return $this->hasOne(UstKategori::class);
        }
    }

类别表 sub cantroy table

There is 2 table for managing categories one for parents and another for sub-categories. When I want to search with this associated field, I can't. and get this error

Error description

  1. Hizmetler Model (Sub-category):
    class Hizmetler extends Model
    {
        protected $primaryKey = 'hizmet_id';
        protected $table = 'hizmetler';
        public $incrementing = false;
    
        use SoftDeletes;
        protected $dates = ['deleted_at'];
        public function Hizmetler(){
            return $this->belongsTo(Hizmetler::class,'hizmet_ust_kategori');
        }
    }
  1. UstKategori Model (Parent category):
    class UstKategori extends Model
    {
        protected $primaryKey = 'id';
        protected $table = 'ust_kategori';
        public $incrementing = false;
    
        use SoftDeletes;
        protected $dates = ['deleted_at'];
        public function UstKategori(){
            return $this->hasOne(UstKategori::class);
        }
    }

Category Table
Sub Categroy Table

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

書生途 2025-02-05 23:18:50

您的关系不正确。根据您的案例,类别与孩子之间的关系是一对

父型:

class UstKategori extends Model
{
    public function childs(){
        return $this->hasMany(Hizmetler::class, 'hizmet_ust_kategori');
    }
}

孩子模型:

class Hizmetler extends Model
{
    public function parent(){
        return $this->belongsTo(UstKategori::class, 'hizmet_ust_kategori');
    }
}

您可以在此处阅读文档和示例: https://laravel.com/docs/9.x/eloquent-relationships#one-to-many

Your relationship is incorrect. according to your case, the relationship between the categories and their child is One to Many.

Parent Model:

class UstKategori extends Model
{
    public function childs(){
        return $this->hasMany(Hizmetler::class, 'hizmet_ust_kategori');
    }
}

Child Model:

class Hizmetler extends Model
{
    public function parent(){
        return $this->belongsTo(UstKategori::class, 'hizmet_ust_kategori');
    }
}

You can read the documentation and examples here: https://laravel.com/docs/9.x/eloquent-relationships#one-to-many

泛泛之交 2025-02-05 23:18:50

我通过在Voyagerbasecontroller中自定义索​​引方法并将该方法复制到我的控制器来解决此问题。
工作步骤如下。

1-将公共功能索引复制到您的控制器

2-替换搜索命令。这些命令在
条件命令if($ search-> value!=''''&& $ search- key&&& $ search-> filter)。

3-删除上述邪恶内容,然后用以下内容替换它:

        if ($search->value != '' && $search->key && $search->filter) {
            if ($search->key == 'model_id' || $search->key == 'color_id')
                $query->where($search->key, $search->value);
            else if ($search->key == 'image_belongsto_color_relationship') {
                $query->whereHas('color', function ($query) use ($search) {
                    if ($search->filter == 'equals') {
                        $query->where('title', $search->value);
                    } else {
                        $query->where('title', 'LIKE', '%' . $search->value . '%');
                    }
                });
            } 
        }

注意:不要忘记在所需模型中定义关系。对于上面的示例,它定义为以下内容:

class Images extends Model
{
    use HasFactory;
    public function color(): BelongsTo
    {
        return $this->belongsTo(Color::class, 'color_id');
    }
}

不要忘记面包旅行者中关系的定义。我的关系定义为属于类型。

I solved this problem by customizing the index method in VoyagerBaseController and copying the method to my controller.
The work steps are as follows.

1- Copy the public function index to your controller

2- Replacing search commands. These commands are inside the
conditional command if ($search->value != '' && $search->key && $search->filter).

3- Remove the above evil content and replace it with the following content:

        if ($search->value != '' && $search->key && $search->filter) {
            if ($search->key == 'model_id' || $search->key == 'color_id')
                $query->where($search->key, $search->value);
            else if ($search->key == 'image_belongsto_color_relationship') {
                $query->whereHas('color', function ($query) use ($search) {
                    if ($search->filter == 'equals') {
                        $query->where('title', $search->value);
                    } else {
                        $query->where('title', 'LIKE', '%' . $search->value . '%');
                    }
                });
            } 
        }

Note: Don't forget to define the relationship in the desired model. For the example above, it is defined as follows:

class Images extends Model
{
    use HasFactory;
    public function color(): BelongsTo
    {
        return $this->belongsTo(Color::class, 'color_id');
    }
}

don't forget the definition of the relationship in Bread Voyager. My relationship is defined as belongTo type.

微暖i 2025-02-05 23:18:50

现在,替换表名“下载” 在您自己的表中。您可以从 yourwebsite.com/admin/database中获得。

在哪里添加: -
转到您的项目目录“供应商/tcg/voyager/resources/views/views/bread/browse.blade.php。fyi

:请确保您在表HREF中使用自己的表替换在下面的表HREF中使用您自己的表。

如果您不适合想编辑此全局模板,然后将其移至资源/供应商/Voyager/yourbreadname/browse.blade.php

<?php
$results = [];
$searchPerformed = false;
if (isset($_GET['search']) && !empty($_GET['search'])) {
    $search = $_GET['search'];
    $results = DB::table('downloads')->where('title', 'LIKE', "%$search%")->get();
    $searchPerformed = true;  // Indicate that a search was executed
}
?>
              
<style>
    .search-container {
        display: flex;
        justify-content: center;
        margin: 20px 0;
    }
    
    .search-bar {
        flex: 1;
        padding: 10px 20px;
        border-radius: 25px;
        border: 1px solid #ccc;
        outline: none;
        transition: border 0.3s;
    }
    
    .search-bar:focus {
        border: 1px solid #007bff; /* This will change border color to blue when the input is focused */
    }
    
    .search-button {
        margin-left: 10px;
        padding: 10px 20px;
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 25px;
        cursor: pointer;
        transition: background-color 0.3s;
    }
    
    .search-button:hover {
        background-color: #0056b3;
    }
</style>

<div class="search-container">
    <form method="GET" action="" style="display: flex; width: 100%; max-width: 1200px;">
        <input type="text" name="search" placeholder="Search by title" value="{{ request('search') }}" class="search-bar">
        <button type="submit" class="search-button">Search</button>
    </form>
</div>



@if($searchPerformed)  <!-- Add this conditional statement -->
<div class="panel panel-bordered">
    <div class="panel-body table-responsive">
        <table id="dataTable" class="row table table-hover">
            <thead>
                <tr>
                    <th>Title</th>
                    <th>Image</th>
                    <th class="actions">Actions</th>
                </tr>
            </thead>
            <tbody>
                @if(count($results) > 0)
                    @foreach($results as $result)
                        <tr>
                            <td>{{ $result->title }}</td>
                            <td>
                                <!-- Display the image -->
                                <img src="{{ url('storage/' . $result->image) }}" alt="{{ $result->title }}" width="100">
                            </td>
                            <td>
                                <!-- View using the slug -->
                                <a href="{{ url('download/' . $result->slug) }}" target="_blank" class="btn btn-sm btn-warning"><i class="voyager-eye"></i> View</a>
                                <a href="{{ url('admin/downloads/' . $result->id . '/edit') }}" target="_blank" class="btn btn-sm btn-primary edit"><i class="voyager-edit"></i> Edit</a>
                                @if (Voyager::can('delete_downloads'))
                                    <a href="javascript:;" title="Delete" class="btn btn-sm btn-danger delete" data-id="{{ $result->id }}" id="delete-{{ $result->id }}">
                                        <i class="voyager-trash"></i> <span class="hidden-xs hidden-sm">Delete</span>
                                    </a>
                                @endif
                            </td>
                        </tr>
                    @endforeach
                @else
                    <tr>
                        <td colspan="3">No results found</td>
                    </tr>
                @endif
            </tbody>
        </table>
    </div>
</div>
@endif  <!-- End of the conditional statement -->

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const deleteButtons = document.querySelectorAll('.delete');

        deleteButtons.forEach(button => {
            button.addEventListener('click', function(e) {
                const id = e.target.getAttribute('data-id');
                
  
                    // Send DELETE request
                    fetch(`admin/downloads/${id}`, {
                        method: 'DELETE',
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        }
                    });
          
            });
        });
    });
</script>

Now Just replace the table name "downloads" to your own table. Which you can get from yourwebsite.com/admin/database.

Where to Add:-
Go to your project directory "vendor/tcg/voyager/resources/views/bread/ browse.blade.php.

FYI: Please make sure you replace the "download" in below table href with your own table to work.

If you don't want to edit this global template then move it to resources/vendor/voyager/yourbreadname/browse.blade.php

<?php
$results = [];
$searchPerformed = false;
if (isset($_GET['search']) && !empty($_GET['search'])) {
    $search = $_GET['search'];
    $results = DB::table('downloads')->where('title', 'LIKE', "%$search%")->get();
    $searchPerformed = true;  // Indicate that a search was executed
}
?>
              
<style>
    .search-container {
        display: flex;
        justify-content: center;
        margin: 20px 0;
    }
    
    .search-bar {
        flex: 1;
        padding: 10px 20px;
        border-radius: 25px;
        border: 1px solid #ccc;
        outline: none;
        transition: border 0.3s;
    }
    
    .search-bar:focus {
        border: 1px solid #007bff; /* This will change border color to blue when the input is focused */
    }
    
    .search-button {
        margin-left: 10px;
        padding: 10px 20px;
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 25px;
        cursor: pointer;
        transition: background-color 0.3s;
    }
    
    .search-button:hover {
        background-color: #0056b3;
    }
</style>

<div class="search-container">
    <form method="GET" action="" style="display: flex; width: 100%; max-width: 1200px;">
        <input type="text" name="search" placeholder="Search by title" value="{{ request('search') }}" class="search-bar">
        <button type="submit" class="search-button">Search</button>
    </form>
</div>



@if($searchPerformed)  <!-- Add this conditional statement -->
<div class="panel panel-bordered">
    <div class="panel-body table-responsive">
        <table id="dataTable" class="row table table-hover">
            <thead>
                <tr>
                    <th>Title</th>
                    <th>Image</th>
                    <th class="actions">Actions</th>
                </tr>
            </thead>
            <tbody>
                @if(count($results) > 0)
                    @foreach($results as $result)
                        <tr>
                            <td>{{ $result->title }}</td>
                            <td>
                                <!-- Display the image -->
                                <img src="{{ url('storage/' . $result->image) }}" alt="{{ $result->title }}" width="100">
                            </td>
                            <td>
                                <!-- View using the slug -->
                                <a href="{{ url('download/' . $result->slug) }}" target="_blank" class="btn btn-sm btn-warning"><i class="voyager-eye"></i> View</a>
                                <a href="{{ url('admin/downloads/' . $result->id . '/edit') }}" target="_blank" class="btn btn-sm btn-primary edit"><i class="voyager-edit"></i> Edit</a>
                                @if (Voyager::can('delete_downloads'))
                                    <a href="javascript:;" title="Delete" class="btn btn-sm btn-danger delete" data-id="{{ $result->id }}" id="delete-{{ $result->id }}">
                                        <i class="voyager-trash"></i> <span class="hidden-xs hidden-sm">Delete</span>
                                    </a>
                                @endif
                            </td>
                        </tr>
                    @endforeach
                @else
                    <tr>
                        <td colspan="3">No results found</td>
                    </tr>
                @endif
            </tbody>
        </table>
    </div>
</div>
@endif  <!-- End of the conditional statement -->

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const deleteButtons = document.querySelectorAll('.delete');

        deleteButtons.forEach(button => {
            button.addEventListener('click', function(e) {
                const id = e.target.getAttribute('data-id');
                
  
                    // Send DELETE request
                    fetch(`admin/downloads/${id}`, {
                        method: 'DELETE',
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        }
                    });
          
            });
        });
    });
</script>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文