5

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

さて、私の質問は次のとおりです。

  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
        (
        )

)
4

2 に答える 2

3
// 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);
于 2013-06-10T19:52:57.530 に答える
3

上記で使用した方法よりも良い関係を生成する方法はありUser -> School/Organizationますか? もしそうなら、どのように?

Eloquent はそれを自動的に処理できるはずです。ここを参照してください: http://three.laravel.com/docs/database/eloquent#inserting-related-models

ユーザーの学校/組織名を取得するより良い方法は次のとおりです。School::find($schoolId)->get()

リレーションシップ情報を取得できず、Elloquent Expressionhas_nameを返すことができない場合でも、必要なオブジェクトまたはコレクションを取得するためにそれらを呼び出す必要があります。belongs_toget()

私がこれに対処した方法は、リレーションシップの引数を追加して、メソッドが式または結果を返す必要があるかどうかを判断することです。

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

...

class User extends Eloquent
{
    /**
     * Return an Elloquent Expression or a collection (or object)
     * Defaults to return a collection
     */
    public function organization ($as_expression=FALSE) {
        $related = $this->belongs_to('Organization');
        return $as_expression ? $related : $related->get();
    }

    public function school ($as_expression=FALSE) {
        $related = $this->belongs_to('School');
        return $as_expression ? $related : $related->get();
    }

    ...

    public function create ($user_data=array()) {
        $newUser = new User;
        $activity = @$user_data['organization'] ?
            'organization' : (@$user_data['school'] ? 'school' : '');

        switch ($activity) {
            case 'organization':
            case 'school':
                /**
                 * Call the corresponding method, return as Eloquent Expression
                 * Use a string to be verbose, TRUE does fine if wanted
                 */
                $new_user->{$activity}('as_expression')->save(array( 'name' => $user_data[$activity]));

                break;
            default:
                break;
        }

        return $new_user;
    }
}

...

class Organization extends Eloquent
{
    public function user ($as_expression=FALSE) {
        $related = $this->has_many('User');
        return $as_expression ? $related : $related->get();
    }
}
于 2013-07-01T08:06:48.553 に答える