GVKun编程网logo

如何通过Laravel雄辩的模型加入三张桌子

7

最近很多小伙伴都在问如何通过Laravel雄辩的模型加入三张桌子这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展Laravel-没有关系的模型雄辩、Laravel雄辩-如何在不创建

最近很多小伙伴都在问如何通过Laravel雄辩的模型加入三张桌子这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展Laravel - 没有关系的模型雄辩、Laravel雄辩-如何在不创建模型的情况下从模型返回查询、Laravel雄辩地如何动态地建立关系?、Laravel雄辩的LEFT JOIN WHERE NULL等相关知识,下面开始了哦!

本文目录一览:

如何通过Laravel雄辩的模型加入三张桌子

如何通过Laravel雄辩的模型加入三张桌子

我有三张桌子

物品表

 id title body categories_id user_id

分类表

  id  category_name

用户表

 id user_name user_type

我想显示其类别名称而不是category_id和user_name而不是user_id的文章,我尝试像这些查询一样工作!

$articles =DB::table(''articles'')                ->join(''categories'', ''articles.id'', ''='', ''categories.id'')                ->join(''users'', ''users.id'', ''='', ''articles.user_id'')                ->select(''articles.id'',''articles.title'',''articles.body'',''users.username'', ''category.name'')                ->get();

但是我想用口才来做。拜托,我该怎么办?

答案1

小编典典

使用Eloquent,它非常容易检索关系数据。在Laravel 5中使用您的场景检查以下示例。

我们有三种模型:

1)文章(属于用户和类别)

2)类别(有很多文章)

3)用户(有很多文章)


1)Article.php

<?phpnamespace App\Models; use Eloquent;class Article extends Eloquent{    protected $table = ''articles'';    public function user()    {        return $this->belongsTo(''App\Models\User'');    }    public function category()    {        return $this->belongsTo(''App\Models\Category'');    }}

2)Category.php

<?phpnamespace App\Models;use Eloquent;class Category extends Eloquent{    protected $table = "categories";    public function articles()    {        return $this->hasMany(''App\Models\Article'');    }}

3)User.php

<?phpnamespace App\Models;use Eloquent;class User extends Eloquent{    protected $table = ''users'';    public function articles()    {        return $this->hasMany(''App\Models\Article'');    }}

您需要了解数据库关系和模型中的设置。用户有很多文章。类别有很多文章。文章属于用户和类别。一旦在Laravel中设置了关系,就可以轻松检索相关信息。

例如,如果要使用用户和类别检索文章,则需要编写:

$article = \App\Models\Article::with([''user'',''category''])->first();

您可以这样使用:

//retrieve user name $article->user->user_name//retrieve category name $article->category->category_name

在另一种情况下,您可能需要检索类别中的所有文章,或检索特定用户的所有文章。您可以这样写:

$categories = \App\Models\Category::with(''articles'')->get();$users = \App\Models\Category::with(''users'')->get();

您可以在http://laravel.com/docs/5.0/eloquent了解更多

Laravel - 没有关系的模型雄辩

Laravel - 没有关系的模型雄辩

正如 Laravel 文档所说,您可以使用 without:https://laravel.com/docs/8.x/eloquent-relationships

模型

protected $with = ['item1','item2','item3','item4'];

控制器

$events = Event::without(['item1','item4'])->get();

Laravel雄辩-如何在不创建模型的情况下从模型返回查询

Laravel雄辩-如何在不创建模型的情况下从模型返回查询

您得到的查询:

$us = User::query()->with('roles','comments','posts')->get();

return response()->json($us);

那会很慢,因为它正在从users表中获取所有数据。此外,从单个API调用返回太多数据往往会失败。

据我所知,对于此类API调用,公司总是对结果进行分页。通过提供offsetlimit,客户总是可以获得更多结果。

$us = User::query()->with('roles','posts')->paginate();

return response()->json($us);

如果您不希望将结果合并到模型中,则可以使用DB门面。但是我认为您不能渴望负载关系。

DB::table('users')->select(...)
    ->join(...)
    ->join(...)
    ->join(...)
    ->get();

Laravel雄辩地如何动态地建立关系?

Laravel雄辩地如何动态地建立关系?

我建议使用 eloquent-dynamic-relation

您可以安装它:

composer require i-rocky/eloquent-dynamic-relation

在模型中使用特征:

    use Rocky\Eloquent\HasDynamicRelation;

class MyModel extends Model {
  use HasDynamicRelation;
}

然后您可以简单地编写:

MyModel::addDynamicRelation('some_relation',function (MyModel $myModel) {
    return $myModel->hasMany(SomeRelatedModel::class);
});

Laravel雄辩的LEFT JOIN WHERE NULL

Laravel雄辩的LEFT JOIN WHERE NULL

我正在尝试使用Eloquent在数据库种子期间执行以下查询:

SELECT    *FROM    customersLEFT JOIN    orders    ON customers.id = orders.customer_idWHERE    orders.customer_id IS NULL

这是我在Eloquent中的实现:

$c = Customer::leftJoin(''orders'', function($join) {      $join->on(''customers.id'', ''='', ''orders.customer_id'');    })    ->whereNull(''orders.customer_id'')    ->first();

尽管第一个查询始终返回完整结果,但Eloquent等价项始终为表的emailphone字段以外的所有内容返回空元素customers。由于CustomersOrders模型都是工匠生成的骨架,因此我无所适从。

例如:

class Customer extends \Eloquent {    // Add your validation rules here    public static $rules = [        // ''title'' => ''required''    ];    // Don''t forget to fill this array    protected $fillable = [];}

这是当我对种子(最初由Faker生成)的第一个口才查询dd()时输出的数组:

protected $original =>  array(25) {    ''id'' =>    NULL    ''first_name'' =>    NULL    ''last_name'' =>    NULL    ''email'' =>    string(24) "luther.braun@example.org"    ''phone'' =>    string(17) "642.150.9176x5684"    ''address1'' =>    NULL    ''address2'' =>    NULL    ''city'' =>    NULL    ''state'' =>    NULL    ''county'' =>    NULL    ''district'' =>    NULL    ''postal_code'' =>    NULL    ''country'' =>    NULL    ''notes'' =>    NULL    ''created_at'' =>    NULL    ''updated_at'' =>    NULL    ''customer_id'' =>    NULL    ''total'' =>    NULL}

答案1

小编典典

可以通过指定特定表中所需的特定列名来解决,如下所示:

$c = Customer::leftJoin(''orders'', function($join) {      $join->on(''customers.id'', ''='', ''orders.customer_id'');    })    ->whereNull(''orders.customer_id'')    ->first([        ''customers.id'',        ''customers.first_name'',        ''customers.last_name'',        ''customers.email'',        ''customers.phone'',        ''customers.address1'',        ''customers.address2'',        ''customers.city'',        ''customers.state'',        ''customers.county'',        ''customers.district'',        ''customers.postal_code'',        ''customers.country''    ]);

今天关于如何通过Laravel雄辩的模型加入三张桌子的介绍到此结束,谢谢您的阅读,有关Laravel - 没有关系的模型雄辩、Laravel雄辩-如何在不创建模型的情况下从模型返回查询、Laravel雄辩地如何动态地建立关系?、Laravel雄辩的LEFT JOIN WHERE NULL等更多相关知识的信息可以在本站进行查询。

本文标签: