数据库的数据输出

Data output from the database

我有一个select,我想从数据库中输出数据

            <select class="select-css" name="title" required="">
                <option selected="" value="" disabled="">Выберите сервер</option>
                @foreach($guilds as $guild)
                    <option value="{{$guild->id}}">{{$guild->name}}</option>
                @endforeach
            </select>

我在 CreateController 中写了这个

$guilds = User::with('guilds')->get('id') === Auth::user()->id;

我有一个 UserGuild 数据库

class UserGuild extends Model
{
    public function user(){
        return $this->hasMany(User::class);
    }
    public function guild(){
        return $this->belongsToMany(Guild::class);
    }
        Schema::create('user_guilds', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->id();
            $table->unsignedBigInteger('user_id')->nullable();
            $table->unsignedBigInteger('guild_id')->nullable();
            $table->index('user_id','user_guild_user_idx');
            $table->index('guild_id','user_guild_guild_idx');
            $table->foreign('user_id','user_guild_user_fk')->on('users')->references('id');
            $table->foreign('guild_id','user_guild_guild_fk')->on('guilds')->references('id');

而我有这样的错误

ErrorException
foreach() argument must be of type array|object, bool given (View: C:\OpenServer\domains\localhost\site-rts\resources\views\main\server\create.blade.php)

我需要将 User Guide 数据库中的内容输出到 select,但同时 {{$guild->name}}value 的值来自 Guild 数据库

我也尝试过使用 foreach,但它不适合我进一步的工作。

                @foreach($users as $user)
                    @foreach($user->guilds as $guild)
                        @if(Auth::user()->id === $user->id)
                              <option value="{{$guild->id}}">{{$guild->name}}</option>
                        @endif
                    @endforeach
                @endforeach

假设模型和迁移是正确的,问题在于查询,在这种情况下返回 boolean 而不是 collection,然后 blade 视图中的 foreach 得到传递 boolean 作为参数而不是 collection 因为它会抛出错误。

因此,您可以使用 where 方法从数据库中获取与您想要的 id 相对应的数据,而不是使用这些条件 === Auth::user()->id;

$guild = User::with('guilds')->where('id', Auth::user()->id)->get();