Laravel красноречивые условные отношения - PullRequest
0 голосов
/ 17 декабря 2018

Я пытаюсь установить условную связь в красноречивой модели на основе значения столбца таблицы, но она не работает.

Это код, который я использую:

 //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 голосов
/ 17 декабря 2018

Принадлежит к отношениям

//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, serveToMany.

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);
    } 

}

Ссылка:

Красноречивая условная связь Ларавела Пример

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...