Laravel模型附加查询

时间:2018-05-25 05:47:41

标签: php laravel eloquent

我在laravel中为表celebrity创建了一个模型,并创建了两个对象,如下所示: -

$obj1 = Celebrity::Select('*');
$obj2 = $obj1;

现在,我想对上面的对象应用不同的条件来从表中获取数据。例如: -

$obj1= $obj1->where('status', 1);

$obj2 = $obj2->where('status', 2);

但是当obj2同时返回Query时。即如果我打印$obj2->toSQL(),则为'Select * from celebrity where stauts =1 and status =2'。但它应该是'Select * from celebrity where status =2'

任何人都可以帮忙吗?我使用的是5.5版本。

3 个答案:

答案 0 :(得分:4)

您不必创建对象。您可以在控制器中执行此操作:

$a = Celebrity::where(['status' => '1'])->get();
$b = Celebrity::where(['status' => '2'])->get();   

答案 1 :(得分:0)

试试这段代码:

$query1 = Celebrity::query();
$query2 = Celebrity::query();

$query1 = $query1->where('status', 1);
$query2 = $query2->where('status', 2);

$result1 = $query1->get();
$result2 = $query2->get();

您可以在此代码中添加条件子句。

答案 2 :(得分:0)

我使用laravel 5.4测试它正在工作

use App\Models\Customer;

Route::get('/', function()
{
    $d1 = Customer::select('*');
    $d2 = Customer::select('*');

    $d1 = $d1->where('name', 'joseph');
    $d2 = $d2->where('name', 'dicdican');

    dd($d1->toSql(), $d2->toSql());

结果:

"select * from `customers` where `name` = ? and `customers`.`deleted_at` is null"

"select * from `customers` where `name` = ? and `customers`.`deleted_at` is null"

如果你介意分享整个代码块?

------更新了

PHP Raw:

$s1 = 'hello';
$s2 = $s1;

$s2 = $s2.' welcome';

dd($s2, $s1);

预期结果:

response