gpt4 book ai didi

php - 我的模型之间的 Laravel 关系

转载 作者:行者123 更新时间:2023-11-29 21:06:10 25 4
gpt4 key购买 nike

我有三个表:

users

该表包含常用的用户数据。 ID、电子邮件、密码、用户名等

teams

Image of my teams table structure

members

Image of my members table structure

我的成员表用于跟踪哪些用户属于哪些团队。

我想要创建的是一条路线,当访问该路线时,会显示用户当前所属的所有团队。

这是我尝试过的:

Team.php

<?php

namespace EG;

use Illuminate\Database\Eloquent\Model;

class Team extends Model
{

protected $table = 'teams';

public function members()
{
return $this->hasMany('Member');
}
}

Member.php

<?php

namespace EG;

use Illuminate\Database\Eloquent\Model;

class Member extends Model
{

protected $table = 'members';

public function teams()
{
return $this->belongsTo('Team');
}
}

routes.php

Route::get('/test', function () {
$member = EG\Member::where('user_id', '=', Auth::user()->id)->get();
$teams = $member->teams;
foreach($teams as $team) {
echo $team->team_name."<br>";
}
});

当我访问/test 时收到此错误:

ErrorException in routes.php line 94: Undefined property: Illuminate\Database\Eloquent\Collection::$teams

为了让你们更好地理解我正在尝试创建的内容,以下是我将如何按程序执行此操作:

$sql = “SELECT team_id FROM members WHERE user_id = ‘“.Auth::user()->id.”';”;
$result = mysqli_querry($conn, $sql);
while ($row = mysqli_fetch_assoc($result))
{
$sql = “SELECT * FROM teams WHERE id = ‘“.$row[’team_id'].”';”;
$result = mysqli_query($conn, $sql);
while ($team = mysqli_fetch_assoc($result))
{
echo $team[’team_name’].”<br>”;
}
}

最佳答案

->get() 方法返回一个集合。

如果您需要单个模型,请使用 ->first() 方法:

$member = EG\Member::where('user_id', '=', Auth::user()->id)->first();

关于php - 我的模型之间的 Laravel 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36811451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com