Laravel:试图获得关系

时间:2014-12-23 23:02:57

标签: php mysql laravel laravel-4

用户:

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');

    public function email_preferences()
    {
        return $this->hasOne('EmailPreference');
    }

}

EmailPreference:

class EmailPreference extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'email_preferences';

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

}

用户

id PK
first_name
last_name
email

email_preferences

id PK
user_id FK (users.id)
newsletter

我试图为用户显示电子邮件首选项:

$user = Auth::user();
echo '<pre>';
print_r($user->email_preferences);
exit;

我一无所获......

1 个答案:

答案 0 :(得分:2)

听起来你想要这样的东西:

<?php
$user = Auth::user();
echo 'Receive newsletter? ' . ($user->emailPreferences->newsletter ? 'Yes' : 'No');

修改

我做了一些挖掘工作发现当在Eloquent函数/属性名称中使用时,下划线可能会很棘手。如果你删除了下划线,事情就应该起作用了:

<?php
class User extends Eloquent implements UserInterface, RemindableInterface {

    public function emailPreferences()
    {
        return $this->hasOne('EmailPreference');
    }

}

请参阅此答案:Laravel 4 Eloquent ORM accessing one-to-one relationship through dynamic properties