2017-07-21 7 views
0

どうすればこのようにすることができますか?これを実現する方法laravel 5雄弁

public function getInformation($model) { 
    $result = $model::with(['province', 'city']); 

    if($model == 'App\Models\Business') { 
    $result->with(['businessProvince', 'businessCity']); 
    } 

    $result->get(); 
} 

// call the function 
$information->getInformation(\App\Models\Business::class); 

私はクラスを照らし\データベースのエラー

オブジェクトを取得しています\雄弁\ Builderは は、上記のサンプルコードで列に

を変換することができませんでした。どんな提案も本当に感謝しています。

答えて

0

これは私の問題を解決しました。皆さんありがとうございます。

public function getInformation($model) { 
    $result = $model::with(['province', 'city']); 

    if($model == 'App\Models\Business') { 
    // my mistake 
    //$result->with(['businessProvince', 'businessCity']); 

    $result = $result->with(['businessProvince', 'businessCity']); 
    } 

    $result->get(); 
} 
2

withが呼び出されたときにクエリが開始されたため、は文字列であり、$resultはEloquent Builderインスタンスであり、モデルクラスのインスタンスではありません。

だから$model == 'App\Models\Business'私は$model === \App\Models\Business::classに変更されますが、それは結果を変えるべきではありません。

このエラーはアプリケーションのこの部分から発生していますか?具体的にどのライン?


オリジナル間違っ答え。

モデルインスタンスを文字列と比較しようとしています($model::with()が渡したモデルクラスのインスタンスを$model引数として作成しているため)。

instanceofキーワードを使用して、インスタンスをクラス名(http://php.net/manual/en/language.operators.type.php)と比較することができます。

if($model instanceof \App\Models\Business) { 
    $result->with(['businessProvince', 'businessCity']); 
} 
+0

上記の示唆から離れて、$ result = $ model :: with(['province'、 'city']); 'else条件のif部分。 – karmendra

+0

これはどうしてやりますか?あなたは$ model :: with(['province'、 'city'、 'businessProvince'、 'businessCity']); 'この' if'部分を入れなければなりません。コードの同じ部分に都道府県と市の熱心な負荷を2回提供する必要があります。 IMHOこれはより読みやすいようです。 –

+0

私の一部では動作しません。私の目標はその方法を再利用することであり、ビジネスモデルだけが「businessProvince」と「businessCity」の関係を持っています。 – Juan