www.91084.com

GVKun编程网logo

如何从与 php laravel 中的枢轴连接的 3 个表中获取数据

14

本文将为您提供关于如何从与phplaravel中的枢轴连接的3个表中获取数据的详细介绍,同时,我们还将为您提供关于Laravel5.2雄辩的ORM从3个表中获取数据、Laravel7-雄辩的ORM在使

本文将为您提供关于如何从与 php laravel 中的枢轴连接的 3 个表中获取数据的详细介绍,同时,我们还将为您提供关于Laravel 5.2雄辩的ORM从3个表中获取数据、Laravel 7-雄辩的ORM在使用一对一关系时从2个表中获取数据、Laravel API:如何从不同表的外键获取数据、Laravel Eloquent 模型无法与多对多关系中的枢轴数据同步的实用信息。

本文目录一览:

如何从与 php laravel 中的枢轴连接的 3 个表中获取数据

如何从与 php laravel 中的枢轴连接的 3 个表中获取数据

我能够通过推荐学习 Eager loading 来解决我的问题

这是我所做的更改

controller

public function index($id)
    {
        $competition = $this->competitionsRepo->findOrFail($id);

        $files = $competition->documents()->with(
            [
                'teams' => function($q) use ($competition) {
                    $q->with([
                        'documents' => function($q) use($competition) {
                            $q->where([
                                'competition_id' => $competition->id,]);
                        }
                    ]);
                },]
        )->get();

        return view('competitions.document',[
            'id'=>$id,'competition'=>$competition,'files'=>$files,]);

    }

在我的 Blade 表中,我使用了 $file->teams->implode('name')

  <table>
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Document Name</th>
                                <th>Assigned Team</th>
                                <th>Date Added</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>

                              @foreach ($files as $key=>$file)
                              <tr>
                                <td>{{ $key+1 }}</td>
                                <td>
                                    <a href="{{ asset('storage/'. $file->file_path) }}"target="_blank">
                                        <img src="{{ asset('/images/sketches/1x/file.png') }}" alt="file">
                                    </a>
                                    {{ $file->name }}
                                </td>

                                <td>
                                    {!! $file->teams->isNotEmpty() ? $file->teams->implode('name') : '<span>No teams selected</span>' !!}
                                </td>
                                <td>{{ $file->created_at->toDateString() }}</td>
                                <td>
                                    <formaction="{{ route('documents.destroy',['competition'=>$id,'document'=> $file->id]) }}" method="POST"
                                        data-confirm-title="Remove Document?"
                                        data-confirm-message="Are you sure you want to remove this document?">
                                        @csrf
                                        @method('DELETE')

                                        <button type="submit" name="button">Remove</button>
                                    </form>
                                </td>
                              </tr>
                              @endforeach
                        </tbody>
 </table>

Laravel 5.2雄辩的ORM从3个表中获取数据

Laravel 5.2雄辩的ORM从3个表中获取数据

您需要使用whereHas和orWhereHas方法在您的条件查询中放置“ where”条件。

请查看https://laravel.com/docs/8.x/eloquent-relationships

$userCollections = Users::where([['users.status','!=','DELETE'],['users.parent_user_id',$clientId],['users.id',$loginUser->id]
  ])
  ->whereHas('userDetails' => function ($query) {
  $query->where('client_team_id',1);
  })->get();

Laravel 7-雄辩的ORM在使用一对一关系时从2个表中获取数据

Laravel 7-雄辩的ORM在使用一对一关系时从2个表中获取数据

我建议通过关系对象访问关系属性。您想将所有属性添加到电话对象,但是在这种情况下,这不是一个很好的做法。

您可以尝试以下方法:

$user = User::first();

$phones = $user->phones()->with('user')->get();

// Then you are able to access user attributes from a phone object like this:
foreach ($phones as $phone) {
    print($phone->user->name);
}

遵循this article:是一种更高级,但又更快,更合适的解决方案:

$user = User::first();

$user->phones->each->setRelation('user',$user);

// Then you are able to access user attributes from a phone object like this:
foreach ($user->phones as $phone) {
    print($phone->user->name);
}
,

跑步时

$results = \App\Models\Users::find(1)->phones;

您还可以包括这样的手机

$results = \App\Models\Users::with('phones')->find(1);

可以通过$results->phones访问该用户的所有电话。

,

在用户模型中添加以下功能:

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

然后,您可以通过手机获取用户:

$user = User::find($id);
$phones = $user->phones()->get();

或:

User::with('phones')->get();
,

资深程序员,感谢您的赞赏。 测试您的解决方案使我弄清楚了如何实现目标。

在简历中:

    $res = User::with('phones')->first();

    echo $res->name'<br>'; 
    foreach($res->phones()->get() as $phone){
        echo $phone->phone_number.'<br>';
    }

这完成了工作。 谢谢@Kevin Bui,@ Mohammad Aliyari和@Douwe de Haan的帮助。

Laravel API:如何从不同表的外键获取数据

Laravel API:如何从不同表的外键获取数据

如何解决Laravel API:如何从不同表的外键获取数据?

我目前想要制作一个 API,该 API 将通过其 module_id 获取所有课程。这些目前是我的代码:

模块迁移表:

<?PHP
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateModulesTable extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up() {
        Schema::create(''modules'',function (Blueprint $table) {
            $table->id();
            $table->string(''module_name'');            
            $table->bigInteger(''created_by'')->unsigned()->nullable(); 
            $table->bigInteger(''updated_by'')->unsigned()->nullable(); 

            $table->timestamps();
        });

        Schema::table(''modules'',function(Blueprint $table) {
            $table->foreign(''created_by'')->references(''id'')->on(''admins'');
            $table->foreign(''updated_by'')->references(''id'')->on(''admins'');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down() {
        Schema::dropIfExists(''modules'');
    }
}

课程迁移表

<?PHP
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateLessonTable extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up() {
        Schema::create(''lesson'',function (Blueprint $table) {
            $table->id();
            $table->string(''title'');
            $table->bigInteger(''module_id'')->unsigned();
            $table->longText(''content'');
            $table->bigInteger(''created_by'')->unsigned()->nullable(); 
            $table->bigInteger(''updated_by'')->unsigned()->nullable(); 
            $table->string(''enabled'')->nullable(); 
            $table->string(''position'')->nullable();
            $table->timestamps();
        });

        Schema::table(''lesson'',function(Blueprint $table) {
            $table->foreign(''module_id'')->references(''id'')->on(''modules'');
            $table->foreign(''created_by'')->references(''id'')->on(''admins'');
            $table->foreign(''updated_by'')->references(''id'')->on(''admins'');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down() {
        Schema::dropIfExists(''lesson'');
    }
}

这是我想要制作的 API 的 GetLessonByModule 控制器(通过其 module_id 获取所有课程):

<?PHP
namespace App\Http\Controllers;
use App\Models\Lesson;
use App\Models\Modules;
use Illuminate\Http\Request;

class GetLessonByModuleController extends Controller {
    public function index() {
        $lessons = Lesson::all();
        return response($lessons,200);
    }
}

module_id 和模块表中的 ID 当前连接,如迁移表中所见。我只是不知道如何在我的控制器中编写它。我也不知道我是否应该制作一个新模型。任何形式的帮助/建议都深表感谢。提前致谢。

解决方法

你可以做到

<?php
namespace App\Http\Controllers;
use App\Models\Lesson;
use App\Models\Modules;
use Illuminate\Http\Request;

class GetLessonByModuleController extends Controller {
    public function index(int $module_id) {
        $lessons = Lesson::where(''module_id'',''='',$module_id)->get();
        return response($lessons,200);
    }
}

在你的 api.php 中应该有路由的定义:

Route::get(''lessons-by-module/{module_id}'',[\App\Http\Controllers::class,''index'']);

如果它适合你并且想要做得更好,你可以使用 Laravel 路由显式绑定:https://laravel.com/docs/8.x/routing#explicit-binding

Laravel Eloquent 模型无法与多对多关系中的枢轴数据同步

Laravel Eloquent 模型无法与多对多关系中的枢轴数据同步

如何解决Laravel Eloquent 模型无法与多对多关系中的枢轴数据同步?

我想同步数据,而不是将数据附加到特定关系。

枢轴关系 usermodel 代码

public function carts(){
        return $this->belongsToMany(Product::class,''user_carts'')->withPivot(''quantity'');
    }

附加代码是

User::find(1)->carts()->attach($s,["quantity"=>1]);

同步代码是

User::find(1)->carts()->sync($s,["quantity"=>1]);

当我尝试编译同步时,那些匹配 user_id = 1 的主元关系在其各自的数量列中没有“1”。

如果我想在不使用attach的情况下实现同步功能,我该怎么做,因为attach()会在我的数据库中创建多个冗余数据。

解决方法

您必须在 sync 方法中传递键值。 假设 $s 是要同步的 ID(键):

User::find(1)->carts()->sync([$s => ["quantity"=>1]]);

今天关于如何从与 php laravel 中的枢轴连接的 3 个表中获取数据的讲解已经结束,谢谢您的阅读,如果想了解更多关于Laravel 5.2雄辩的ORM从3个表中获取数据、Laravel 7-雄辩的ORM在使用一对一关系时从2个表中获取数据、Laravel API:如何从不同表的外键获取数据、Laravel Eloquent 模型无法与多对多关系中的枢轴数据同步的相关知识,请在本站搜索。

本文标签: