Laravel雄辩的条件关系

时间:2018-12-17 02:00:03

标签: php laravel eloquent

我正在尝试根据表列的值在雄辩的模型中建立条件关系,但这不起作用。

这是我正在使用的代码:

 //RELATIONS
public function task_schedule()
{
    if ($this->task_schedule_id === 0) {
        return $this->belongsTo('TaskSchedule', 'hold_task_schedule_id', 'id');
    } else {
        return $this->belongsTo('TaskSchedule');
    }

}

基本上,我想使用不同的列来获取我的子模型在属于关系中定义。

scopeProfile($ query)对我不起作用,因为我不想在每个查询中都检索该孩子,并且我在很多地方都使用Task-> with('task_schedule')代码。

1 个答案:

答案 0 :(得分:0)

属于关系

//associate
$account = App\Account::find(10);
$user->account()->associate($account);
$user->save();

//dissociate
$user->account()->dissociate();
$user->save();

// * Get the author of the post.
public function user()
{
    return $this->belongsTo('App\User')->withDefault();
}


//Get the author of the post.
public function user()
{
    return $this->belongsTo('App\User')->withDefault([
        'name' => 'Guest Author',
    ]);
}

//Get the author of the post.
public function user()
{
    return $this->belongsTo('App\User')->withDefault(function ($user) {
        $user->name = 'Guest Author';
    });
}

这四个方法中的四个是hasMany,hasOne,belongsTo,belongsToMany。

class Country extends Model
{
    public function neighbors()
    {
        return $this->hasMany(\App\Country::class);
    }

    public function president(){
        return $this->hasOne(\App\Person::class);
    }

    public function continent(){
        return $this->belongsTo(\App\Continent::class);
    }

    public function associations(){
        return $this->belongsToMany(\App\Association::class)->using(\App\CountryAssociation::class);
    } 

}

参考文献:

Laravel eloquent conditional relationship Example

相关问题