【问题标题】:Laravel inserting and retrieving relationshipsLaravel 插入和检索关系
【发布时间】:2013-06-06 12:40:26
【问题描述】:

我正在开发一个基于 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
        (
        )

)

【问题讨论】:

    标签: php orm laravel relationship eloquent


    【解决方案1】:
    // 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);
    

    【讨论】:

    • 问题在于,目前还没有自动完成功能,因此任何输入都是新输入,没有现有的 ID,只有组织的名称。所以我也必须插入组织,并与用户相关
    【解决方案2】:

    有没有更好的方法来生成User -> School/Organization 关系,然后是上面使用的那个?如果有,怎么做?

    Eloquent 应该能够自动处理它,请看这里:http://three.laravel.com/docs/database/eloquent#inserting-related-models

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

    如果您的意思是无法检索关系信息:has_namebelongs_to 返回 Elloquent Expression,您仍然需要对它们调用 get() 以检索您想要的对象或集合。

    我处理这个问题的方法是为关系添加一个参数以确定该方法是否应该返回表达式或结果:

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

    【讨论】:

    • 有意思,我会尽快试一试,然后告诉你
    猜你喜欢
    • 2014-09-23
    • 2016-10-05
    • 2022-01-10
    • 2020-08-23
    • 2023-03-26
    • 2020-08-30
    • 1970-01-01
    • 2020-08-20
    • 2017-03-21
    相关资源
    最近更新 更多