drxt70655 2015-05-21 08:48
浏览 642
已采纳

获取模型的ID并使用Laravel HasManyThrough关系更新字段时出错

I have created 3 laravel models Organization, User & Contact which have a Laravel HasManyThrough relation.

I have defined all the required relationships for the Models.

I have to update a specific field named 'deletedate' of a contact which belongs to an Organization.

I used the following code:

class ContactsController extends BaseController
{
    function __construct()
    {
        $this->user= User::find(Auth::id());
        $this->organization = $this->user->organization;
    }

    public function update_it()
    {
        $contact = $this->organization->contact()->find(Input::get('id'));

        $contact->deletedate = Carbon\Carbon::now()->toDateTimeString();

        print $contact->name;

        print $contact->id;

        $contact->save();
    }
}

In the function function update_it(),

While fetching the data, all the fields of a contact which belongs to that specific Input “id” is extracted except the field “id”. Instead of fetching the id of the Contact, the id of User is bieng fetched.

print $contact->name This code returns the exact name of the contact that belongs to the input id.

print $contact->id While this code returns the id of the User.

$contact->save() This code updates the contact's “deletedate” field whose id is equal to user_id.

Defenition of the three models is given below:

Organization Model :

class Organization extends Eloquent 
{       
    protected $table = 'organizations';

    public function contact()
    {
        return $this->hasManyThrough('Contact', 'User', 'organization_id', 'user_id');
    }
}

User Model:

class User extends Eloquent 
{
    protected $table = 'users';
    public function contact()
    {
        return $this->hasMany('Contact');
    }

    public function organization()
    {
        return $this->belongsTo('Organization');
    }
}

Contact Model:

class Contact extends Eloquent 
{
    protected $table = 'contacts';
    public function user()
    {
        return $this->belongsTo('User');
    }
}

展开全部

  • 写回答

1条回答 默认 最新

  • douba1617 2015-05-22 00:23
    关注

    From the Eloquent documentation you can see that calling the find method fetches all columns from the query generated. So in your case you have two tables joined contacts and users and users table id overwrites the contacts id.

    In order to fetch only Contact fields, just specify the columns you want in find method like this:

    $contact = $this->organization->contact()->find(Input::get('id'), ['contacts.*']);
    

    And then you will have only contact data loaded and the id will be the correct one :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部