首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我定义了两个表之间的多到多的关系,并成功地运行了迁移和播种机。但这不起作用

我定义了两个表之间的多到多的关系,并成功地运行了迁移和播种机。但这不起作用
EN

Stack Overflow用户
提问于 2022-06-02 09:46:33
回答 1查看 48关注 0票数 0

我想在用户和计划之间建立许多到多个关系。

这是我的用户模型

代码语言:javascript
复制
<?php

namespace App\Models;

use App\Models\Major;
use App\Models\Score;
use App\Models\Schedule;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    

    protected $guarded=['id'];
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function getRouteKeyName()
    {
        return 'name';
    }

    public function score(){
        return $this->hasMany(Score::class);
    }
    
    public function major(){
        return $this->hasOne(Major::class,'id','major_id');
    }

    public function schedule(){
        return $this->belongsToMany(Schedule::class,'schedule_user','user_id','schedule_id');
        // 'schedule_user','user_id','schedule_id'
    }

    protected function type(): Attribute
    {
        return new Attribute(
            get: fn ($value) =>  ["mahasiswa", "dosen","admin"][$value],
        );
    }
}

这是我的时间表模型

代码语言:javascript
复制
<?php

namespace App\Models;

use App\Models\User;
use App\Models\Course;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Schedule extends Model
{
    use HasFactory;
    protected $guarded=['id'];

    public function course(){
        return $this->belongsTo(Course::class);
    }
    public function user(){
        return $this->belongsToMany(User::class,'schedule_user','schedule_id','user_id');
    }
    
}

create_users_table

代码语言:javascript
复制
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            // $table->unsignedBigInteger('major_id');
            $table->foreignId('major_id')->constrained('majors');
            // $table->foreign('major_id')->references('id')->on('majors');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password')->default('password123');
            $table->bigInteger('nrp');
            $table->string('address');
            $table->integer('generation');
            $table->integer('type')->default(0);
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

create_schedules_table

代码语言:javascript
复制
<!-- create_schedules_table -->
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateSchedulesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('schedules', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->nullable();
            $table->foreignId('course_id')->constrained('courses')->nullable();
            $table->timestamps();
            $table->string('Hari');
            $table->string('Jam');
            

        });
    }

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

create_schecule_user_table.php

代码语言:javascript
复制
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateScheduleUserTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('schedule_user', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->foreignId('user_id')->constrained('users')->nullable();
            $table->foreignId('schedule_id')->constrained('schedules')->nullable();
        });
    }

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

这是我的控制器..。我试着显示用户时间表,用户的id=1

代码语言:javascript
复制
<?php

namespace App\Http\Controllers;

use App\Models\Schedule;
use App\Models\User;
use Illuminate\Http\Request;

class ScheduleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $user=User::find(1);
        return view('schedule.index',[

            'title'=>'Jadwal Kuliah',
            'schedules'=>$user->schedule
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Schedule  $schedule
     * @return \Illuminate\Http\Response
     */
    public function show(Schedule $schedule)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Schedule  $schedule
     * @return \Illuminate\Http\Response
     */
    public function edit(Schedule $schedule)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Schedule  $schedule
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Schedule $schedule)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Schedule  $schedule
     * @return \Illuminate\Http\Response
     */
    public function destroy(Schedule $schedule)
    {
        //
    }
}

这是schedule.index

代码语言:javascript
复制
@extends('dashboard.layouts.main')

@section('container')
<h3>schedule Kuliah {{auth()->user()->name}}</h3>
<table class="table align-items-center justify-content-center mb-0">
    <thead>
      <tr>
        <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Mata Kuliah</th>
        <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2">Hari</th>
        <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2">Jam</th>
        <th></th>
      </tr>
    </thead>
    <tbody>

    @foreach ($schedules as $schedule)
      <tr>
        <td>
          <div class="d-flex px-2">
            <div class="my-auto">
              <h6 class="mb-0 text-sm">{{$schedule->course->nama_mata_kuliah}}</h6>
            </div>
          </div>
        </td>
        <td>
          <p class="text-sm font-weight-bold mb-0">{{ $jadwak->hari }}</p>
        </td>
        <td>
          <span class="text-xs font-weight-bold">{{ $schedule->jam }}</span>
        </td>
      </tr>
      @endforeach
    </tbody>
  </table>

@endsection

未显示任何用户日程的视图。当我使用php tinker签入终端时,调度::first()->user返回: all:[]

EN

回答 1

Stack Overflow用户

发布于 2022-06-02 10:04:40

如果这是很多种关系,我认为这是行不通的

代码语言:javascript
复制
$schedule->course->nama_mata_kuliah

因为$schedule将返回相关对象的数组,而不是单个对象,即使我们只有一个与用户相关的调度。

你必须使用循环

代码语言:javascript
复制
 foreach($user->schedule as $sch) {
//do something.
 }

一个建议,如果你有一个多到多的关系,建议给你的关系函数的复数名称。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72474142

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档