【问题标题】:Laravel model object chainingLaravel 模型对象链接
【发布时间】:2014-02-23 15:29:46
【问题描述】:

由于某种原因,我无法链接模型对象。我正在尝试为“订单”加载“位置”,并且希望将逻辑包含在模型本身中。但是过了一个链就不行了。

class Order extends Eloquent {
    protected $table = 'orders';

    public function customer() {
        return $this->belongsTo('Customer');

    public function location() {
        return $this->customer()->location(); // this does not work
    }
}

class Customer extends Eloquent {
    protected $table = 'customers';

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

    public function orders() {
        return $this->hasMany('Order');
    }

    public function location() {
        return $this->user()->location();
            // return $this->user(); // WORKS!!
    }
}

class User extends Eloquent {
    protected $table = 'users';

    public function locations() {
        return $this->hasMany('Location');
    }

    public function location() {
        return $this->locations()->first();
    }
}

我最终想这样做:

class ChefController extends BaseController {
    public function get_orders() {
        $chef = $this->get_user_chef(); // this already works
        return $chef->orders()->with('location')->get(); // does not work
    }
}

【问题讨论】:

    标签: php orm laravel eloquent


    【解决方案1】:

    尝试通过添加 user_id 作为第二个参数来引用关系(用户表),如下所示:

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

    也许你称那个 id 字段不同,但你知道我的意思。

    【讨论】:

    • 这不是默认的吗?
    • 好吧,当你命名你的方法而不是模型名称时,你必须明确 id。
    • 方法名与模型不同?
    • 例如,您可以调用您的方法所有者,并提供属于的原始方法的正确 ID。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 1970-01-01
    相关资源
    最近更新 更多