如何使用with运算符改进Laravel代码?

时间:2017-03-19 20:39:35

标签: laravel laravel-5.4

在我对DB的请求中,我使用Laravel的模型和函数interface MyFunc<T> { boolean func(T v1, T v2); } class HighTemp { private int hTemp; HighTemp(int ht) { hTemp = ht; } boolean sameTemp(HighTemp ht2) { return hTemp == ht2.hTemp; } boolean lessThanTemp(HighTemp ht2) { return hTemp < ht2.hTemp; } } public class InstanceMethObjectRefDemo { static<T> int Counter(T[] vals, MyFunc<T> f, T v) { int count = 0; for (int i = 0; i < vals.length; i++) if (f.func(vals[i], v)) count++; return count; } public static void main(String[] args) { int count; HighTemp[] weekDayHighs = { new HighTemp(89), new HighTemp(82), new HighTemp(90), new HighTemp(89), new HighTemp(89), new HighTemp(91), new HighTemp(84), new HighTemp(83) }; count = Counter(weekDayHighs, HighTemp::sameTemp, new HighTemp(89)); System.out.println(count + " days had a high of 89"); HighTemp[] weekDayHighs2 = { new HighTemp(32), new HighTemp(12), new HighTemp(24), new HighTemp(19), new HighTemp(18), new HighTemp(12), new HighTemp(-1), new HighTemp(13) }; count = Counter(weekDayHighs2, HighTemp::sameTemp, new HighTemp(12)); System.out.println(count + " days had a high of 12"); count = Counter(weekDayHighs, HighTemp::lessThanTemp, new HighTemp(89)); System.out.println(count + " days had a high less than 89"); count = Counter(weekDayHighs2, HighTemp::lessThanTemp, new HighTemp(19)); System.out.println(count + " days had a high of less then 19"); } } ,如:

with

问题是如果要在模板中执行以下操作:

$user = User::with("city")->get();

只有当用户指定了city时才会起作用,因此数据库表中存在value。否则返回错误:

如何摆脱多余的支票,如:

{{$user->city()->name}}

这太棒了!

1 个答案:

答案 0 :(得分:5)

在模型上定义关系时,请使用withDefault方法:

class User extends Model
{
    public function city()
    {
        return $this->hasOne(City::class)->withDefault();
    }
}

有了这个,$user->city将始终返回City模型。

相关问题