gpt4 book ai didi

php - Laravel 插入和检索关系

转载 作者:可可西里 更新时间:2023-11-01 14:03:38 27 4
gpt4 key购买 nike

我正在开发一个基于 Laravel 3 的项目,我正在尝试查看是否可以缩短处理关系的代码(更好的方法来执行以下操作)

用户 Controller

创建用户函数

$newUser = new User;

if($userData['organization'])
$newUser->organization = self::_professional('Organization', $newUser, $userData);
else
$newUser->school = self::_professional('School', $newUser ,$userData);

创建或检索学校/组织 ID

private function _professional($type, $newUser, $userData)
{
if ( $orgId = $type::where('name', '=', $userData[strtolower($type)])->only('id'))
return $orgId;
else
{
try {
$org = $type::create(array('name' => $userData[strtolower($type)]));
return $org->attributes['id'];
} catch( Exception $e ) {
dd($e);
}
}
}

模型

用户模型

class User extends Eloquent {

public function organization()
{
return $this->belongs_to('Organization');
}

public function school()
{
return $this->belongs_to('School');
}
}

组织/学校模型

class Organization extends Eloquent {

public function user()
{
return $this->has_many('User');
}

}

迁移

用户迁移

....
$table->integer('organization_id')->unsigned()->nullable();
$table->foreign('organization_id')->references('id')->on('organizations');

$table->integer('school_id')->unsigned()->nullable();
$table->foreign('school_id')->references('id')->on('schools');
....

组织/学校迁移

....
$table->increments('id');
$table->string('name');
$table->string('slug');
$table->integer('count')->default(1)->unsigned();
....

现在,我的问题是:

  1. 有没有比上面使用的更好的生成用户 -> 学校/组织关系的方法?如果是,怎么办?

  2. 检索用户学校/组织名称的更好方法是:School::find($schoolId)->get()

执行User::find(1)->school() 不会检索school 的任何数据,仅:

[base:protected] => User Object
(
[attributes] => Array
(
[id] => 1
[nickname] => w0rldart
....
[organization_id] =>
[school_id] => 1
...
)
[relationships] => Array
(
)

[exists] => 1
[includes] => Array
(
)

)

[model] => School Object
(
[attributes] => Array
(
)

[original] => Array
(
)

[relationships] => Array
(
)

[exists] =>
[includes] => Array
(
)

)

最佳答案

// You have to save this before you can tied the organizations to it
$new_user->save();

// The organizations that you want to tie to your user
$oganization_ids = array(1, 2, 3);

// Save the organizations
$result = $new_user->organization()->sync($oganization_ids);

关于php - Laravel 插入和检索关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17030984/

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