在Eloquent ORM中使用has_many_and_belongs_to时选择列


Selecting columns while using has_many_and_belongs_to in Eloquent ORM

我有三个表,placesplace_userusers。我想使用has_many_and_belongs_to方法,根据place_user表中的就地模型列出users。但我不想选择所有列的用户。我试着通过以下方式做到:

Place::find(1)->users()->get(array('name','email'));

Place::find(1)->users()->first(array('name','email'));

但它们没有起作用。

处理这个问题的最佳方法是什么?

地点型号:

class Place extends Eloquent {
    public static $timestamps = true;
    public function users() {
        return $this->has_many_and_belongs_to('user');
    }
}

用户模型

class User extends Eloquent {
    public static $timestamps = true;
    public function get_updated_at_readable() {
        return date('d.m.Y / H:i:s', strtotime($this->get_attribute('updated_at')));
    }
    public function get_created_at_readable() {
        return date('d.m.Y / H:i:s', strtotime($this->get_attribute('updated_at')));
    }
    public function places() {
        return $this->has_many_and_belongs_to('place','place_user');
    }
}

谢谢。

仍然不使用get,first方法,但select方法有效:

Place::find(1)->users()->select(array('users.name', 'users.email'))->get();

我觉得这会导致错误,因为Place和User表中的一列或两列"name"/"email"都不明确。

在您的解决方案中,您可以编写指定表的列:

Place::find(1)->users()->get(array('users.name','users.email'));