php – Laravel插入和检索关系

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

用户控制器

创建用户功能

$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();
....

现在,我的问题是:

>有没有更好的方法生成用户 – >学校/组织关系,那么上面使用的那个?如果是这样,怎么样?
>通过执行以下操作检索用户的学校/组织名称的更好方法:School :: find($schoolId) – > get()

做User :: find(1) – > 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);

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...